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

我有一个名为的文本文件 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可能大于该值。我怎么解决这个问题?


一只甜甜圈
浏览 580回答 3
3回答

一只斗牛犬

最简单的方法是读取一个字符,并在阅读后立即打印: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 */}fscanf()使用%sas格式的方法会丢失有关文件中空格的信息,因此不会将文件复制到stdout。

慕码人2483693

而是直接将字符打印到控制台上,因为文本文件可能非常大,您可能需要大量内存。#include <stdio.h>#include <stdlib.h>int main() {&nbsp; &nbsp; FILE *f;&nbsp; &nbsp; char c;&nbsp; &nbsp; f=fopen("test.txt","rt");&nbsp; &nbsp; while((c=fgetc(f))!=EOF){&nbsp; &nbsp; &nbsp; &nbsp; printf("%c",c);&nbsp; &nbsp; }&nbsp; &nbsp; fclose(f);&nbsp; &nbsp; return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP