为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C
一只甜甜圈 2019-09-20 16:04:00
我有一个名为的文本文件 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可能大于该值。我怎么解决这个问题?
查看完整描述

3 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

最简单的方法是读取一个字符,并在阅读后立即打印:


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。


查看完整回答
反对 回复 2019-09-20
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

而是直接将字符打印到控制台上,因为文本文件可能非常大,您可能需要大量内存。


#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;

}


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 582 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信