一、标准I/O函数:
1.fopen/fclose
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);
返回值:成功返回文件指针,错误返回NULL ,并设置errno,FILE *指针称为不透明指针(Opaque Pointer)或句柄(handle) 。
int fclose(FILE *fp);
返回值:成功返回0,错误返回EOF ,并设置errno
2.stdin/stdout/stderr
因为在程序启动时(在main函数还没开始执行之前)会自动把终端设备打开三次,分别赋给三个FILE *指针stdin、stdout和stderr,这三个文件指针是libc中定义的全局变量,在stdio.h中声明,printf向stdout写,而scanf从stdin读,后面我们会看到,用户程序也可以直接使用这三个文件指针。
if ((fp = fopen("/hom/download/file1","r")) == NULL)
{
fputs("ERROR open file /home/download/file1/n",stderr);
exit(1);
}
3.errno与perror函数
很多系统函数在错误返回时将错误原因记录在libc定义的全局变量errno中,打印errno时,打印出来的只是一个整数值,所以用perror或strerror函数將errno解释成字符串再打印。一个系统函数错误返回后应马上检查errno,在检查errno之前不能再调用其他系统函数。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
FILE *fp = fopen("abcd","r");
if(fp ==NULL)
{
//perror("Open file abcd");
printf("errno: %d/n",errno);
exit(1);
}
return 0;
}
结果:
errno: 2
如果不注销//perror("Open file abcd");此行的结果为:
Open file abcd: No such file or directory
errno: 29
strerror函数可以根据错误号返回错误原因字符串。
#include <string.h>
char *strerror (int errnum);
有些函数的错误码并不保存在errno中,而是通过返回值返回,就不能调用perror打印错误原因了,这时strerror就派上用场了fputs(strerror(n),stderr);
4.以字节为单位的I/O函数:fgetc/fputc/getchar/putchar
int fgetc(FILE *stream);
int getchar(void); //相当于调用fgetc(stdin)
返回值:成功返回读到的字节,出错或读到文件末尾时返回EOF
int fputc (int c,FILE *stream);
int putchar(int c);//相当于调用fputc(c,stdout)
返回值:成功返回写入的字节,出错返回EOF
例子:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp; int ch;
if ( (fp = fopen("file2", "w+")) == NULL)
{
perror("Open file file2/n");
exit(1);
}
while ( (ch = getchar()) != EOF)
fputc(ch, fp);
rewind(fp); //将文件指针重新指向一个流的开头
while ( (ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}
编写一个简单的文件拷贝程序:
#include <stdio.h>
int main(int argc,char *argv[])
{
FILE *input,*output;
int letter;
char *srcFile=NULL;
char *szTargetFile=NULL;
srcFile=argv[1];
szTargetFile=argv[2];
if((input = fopen(srcFile,"r")) == NULL)
{
printf("can't open %s /n",argv[1]);
}
else if((output = fopen(szTargetFile,"w")) == NULL)
{
printf("can't open %s /n",argv[2]);
}
else
{
while((letter = fgetc(input)) != EOF)
{
fputc(letter,output);
}
fclose(input);
fclose(output);
}
return 0;
}
5.操作读写位置的函数:fseek/ftell/rewind
int fseek(FILE *stream, long offset. int whence); //whence:SEEK_SET(从开头移动offset个字节),SEEK_CUR,SEEK_END
返回值:成功返回0,出错返回