//C库函数读取文件的代码
I/O缓冲机制 C语言库函数写文件都是写在内存中,然后一次写入磁盘。提高了效率。
读写文件,不对系统进行操作,一般采用C语言库函数。移植可以在任何可以对C支持的操作系统,而不用修改。
FILE *fopen(const char *path, const char *mode);
mode 参数:
r Open text file for reading. The stream is positioned at the beginning of the file.
r+ Open for reading and writing. The stream is positioned at the beginning of the file.
w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does not exist, otherwiseit is truncated. The stream is positioned at the beginning of the file.
a Open for appending (writing at end of file). The file is created if it does notexist. The stream is positioned at the end of the file.
a+ Open for reading and appending (writing at end of file). The file is created if itdoes not exist. The initial file position for reading is at the beginning of the
file, but output is always appended to the end of the file.
r 读的方法打开文件,文件的开始开始读
r+ 读和写,位置也是在文件的开始
w 截断文件(清空)并创建文件 写入,位置也是文件开始
w+ 读写文件,如果文件不存在就创建文件,存在就截断文件,位置也是文件开始。
a 追加写入的方式打开文件,如果文件不存在就创建文件,位置在文件尾部
a+ 打开追加文件读写。如果文件不存在,则创建文件。
int fclose(FILE *fp);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size 表示读的大小,nmemb表示读记录次数。
如100个字符的buff 可以读size =100, nmemb =1
也可以size =1 ,nmemb =100
每次读满size的时候才有返回,否则为0
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
int main(int arg, char *args[])
{
FILE *p = fopen(args[1], "r+");
if (p == NULL)
{
printf("error is %s\n", strerror(errno));
}
else
{
printf("success\n");
char buf[100];
size_t rc = 0;
while(1)
{
size_t tmp = fread(buf, 1, sizeof(buf), p);//原则是第二个参数乘以第三个参数的大小不能超过缓冲区
rc += tmp;
if (tmp == 0)
break;
}
printf("rc = %d\n", rc);
fclose(p);
}
return 0;
}