在C中,我应该如何读取文本文件并打印所有字符串

您所在的位置:网站首页 C语言文件读取字符串 在C中,我应该如何读取文本文件并打印所有字符串

在C中,我应该如何读取文本文件并打印所有字符串

2024-04-26 11:45| 来源: 网络整理| 查看: 265

最简单的方法是读取一个字符,并在读取后立即打印出来:

代码语言:javascript复制int c; FILE *file; file = fopen("test.txt", "r"); if (file) { while ((c = getc(file)) != EOF) putchar(c); fclose(file); }

c是上面的int,因为EOF是一个负数,一个普通的char可能是unsigned。

如果您想按块读取文件,但没有动态内存分配,您可以这样做:

代码语言:javascript复制#define CHUNK 1024 /* read 1024 bytes at a time */ char buf[CHUNK]; FILE *file; size_t nread; file = fopen("test.txt", "r"); if (file) { while ((nread = fread(buf, 1, sizeof buf, file)) > 0) fwrite(buf, 1, nread, stdout); if (ferror(file)) { /* deal with error */ } fclose(file); }

上面的第二种方法本质上就是如何读取具有动态分配的数组的文件:

代码语言:javascript复制char *buf = malloc(chunk); if (buf == NULL) { /* deal with malloc() failure */ } /* otherwise do this. Note 'chunk' instead of 'sizeof buf' */ while ((nread = fread(buf, 1, chunk, file)) > 0) { /* as above */ }

使用%s作为格式的fscanf()方法会丢失有关文件中空格的信息,因此它并不完全是将文件复制到stdout。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3