最简单的方法是读取字符,并在读取后立即打印:
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
.
如果您想分块读取文件,但不需要动态内存分配,可以执行以下操作:
#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 */
}
用%s
作为格式的方法会丢失有关文件中空白的信息,因此它并不完全是将文件复制到stdout
.