3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個(gè)贊
最簡(jiǎn)單的方法是讀取一個(gè)字符,并在閱讀后立即打?。?/p>
int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
c在int上面,因?yàn)镋OF是負(fù)數(shù),而平原char可能是unsigned。
如果要以塊的形式讀取文件,但沒有動(dòng)態(tài)內(nèi)存分配,則可以執(zhí)行以下操作:
#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);
}
上面的第二種方法實(shí)質(zhì)上是如何使用動(dòng)態(tài)分配的數(shù)組讀取文件:
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()使用%sas格式的方法會(huì)丟失有關(guān)文件中空格的信息,因此不會(huì)將文件復(fù)制到stdout。

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
而是直接將字符打印到控制臺(tái)上,因?yàn)槲谋疚募赡芊浅4?,您可能需要大量?jī)?nèi)存。
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f;
char c;
f=fopen("test.txt","rt");
while((c=fgetc(f))!=EOF){
printf("%c",c);
}
fclose(f);
return 0;
}
- 3 回答
- 0 關(guān)注
- 637 瀏覽
添加回答
舉報(bào)