最简单的方法是读取字符,并在阅读后立即打印:
int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
c是int,因为EOF是负数,并且纯字符可以是无符号的。
如果你想读取块中的文件,但没有动态内存分配,你可以做:
#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);
}
上面的第二种方法本质上是如何使用动态分配的数组读取文件:
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 */
}
您的方法fscanf()与%s作为格式丢失文件中的空格的信息,因此它不是完全复制文件到标准输出。