当前位置: 首页 > 图文教程 > 开发语言 > C/C++ > C/C++:小编谈C语言函数那些事(16)
C程序是由一组或是变量或是函数的外部对象组成的。 函数是一个自我包含的完成一定相关功能的执行代码段。下面小编和大家分享下C语言中的函数。
1. qsort函数
qsort函数的功能是使用快速排序例程进行排序,其用法为:void qsort(void *base, int nelem, int width, int (*fcmp)());程序实例如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sort_function( const void *a, const void *b);
char list[5][4] = { "cat", "car", "cab", "cap", "can" };
int main(void)
{
int x;
qsort((void *)list, 5, sizeof(list[0]), sort_function);
for (x = 0; x < 5; x++)
printf("%s\n", list[x]);
return 0;
}
int sort_function( const void *a, const void *b)
{
return( strcmp(a,b) );
}
2. putw函数
putw函数的功能是把一字符或字送到流中,其用法为int putw(int w, FILE *stream);程序实例代码如下:
#include <stdio.h>
#include <stdlib.h>
#define FNAME "test.$$$"
int main(void)
{
FILE *fp;
int word;
fp = fopen(FNAME, "wb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
word = 94;
putw(word,fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);
fclose(fp);
unlink(FNAME);
return 0;
}
3. puttext函数
puttext函数的功能是将文本从存储区拷贝到屏幕, 其用法为:int puttext(int left, int top, int right, int bottom, void *source);程序实例代码如下:
#include <conio.h>
int main(void)
{
char buffer[512];
clrscr();
gotoxy(20, 12);
cprintf("This is a test. Press any key to continue ...");
getch();
gettext(20, 12, 36, 21,buffer);
clrscr();
gotoxy(20, 12);
puttext(20, 12, 36, 21, buffer);
getch();
return 0;
}
4. putenv函数
putenv函数的功能是把字符串加到当前环境中,其用法为:int putenv(char *envvar);程序实例代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
#include <string.h>
#include <dos.h>
int main(void)
{
char *path, *ptr;
int i = 0;
ptr = getenv("PATH");
path = malloc(strlen(ptr)+15);
strcpy(path,"PATH=");
strcat(path,ptr);
strcat(path,";c:\\temp");
putenv(path);
while (environ[i])
printf("%s\n",environ[i++]);
return 0;
}
评论 (0) All