我有一个名为test.txt
的文本文件
我想编写一个 C 程序来读取该文件并将内容打印到控制台(假设该文件仅包含 ASCII 文本)。
我不知道如何获取字符串变量的大小。像这样:
char str[999];
FILE * file;
file = fopen( "test.txt" , "r");
if (file) {
while (fscanf(file, "%s", str)!=EOF)
printf("%s",str);
fclose(file);
}
大小 999
不起作用,因为 fscanf
返回的字符串可能大于该值。我该如何解决这个问题?
最佳答案
最简单的方法是读取一个字符,读完后立即打印:
int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
c
是上面的 int
,因为 EOF
是负数,而普通的 char
可能是 无符号
。
如果你想分块读取文件,但没有动态内存分配,你可以这样做:
#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
作为格式的 fscanf()
方法会丢失有关文件中空格的信息,因此它并没有完全将文件复制到 stdout
.
关于c - 在C中,我应该如何读取文本文件并打印所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58215568/