简体   繁体   English

C 编程:从文件中读取并打印到控制台

[英]C programming: Reading from file and printing to console

Good evening,晚上好,

I know there's similar questions, which I have been sifting through, but this particular issue seems to be unique.我知道有类似的问题,我一直在筛选,但这个特定的问题似乎是独一无二的。

I am attempting to figure out how to simply read a text file into a string, and then write the string to standard output.我试图弄清楚如何简单地将文本文件读入字符串,然后将字符串写入标准输出。 I tried this code, but nothing is happening in the console when I call puts().我试过这段代码,但是当我调用 puts() 时,控制台中什么也没发生。 The file.txt generates properly with "hello" written, but the last if statement doesn't seem to work for some reason since it does not reach my test condition. file.txt 正确生成并写入了“hello”,但最后一个 if 语句由于某种原因似乎不起作用,因为它没有达到我的测试条件。 How can I make this functional?我怎样才能使这个功能?

This was the code given by many, many examples online, only slightly modified:这是网上很多很多例子给出的代码,只是稍微修改了一下:

#include <stdio.h>

int main()
{
    FILE *fp;
    char str[60];

    fp = fopen("file.txt","w+");
    fprintf(fp,"%s","hello");
    if(fp==NULL){
        perror("Error opening file");
        return(-1);
    }
    if (fgets (str, 60, fp)!=NULL)
        puts(str);
        printf("%s","test");
    fclose(fp);
return 0;
}

写入文件后,必须fclose() fp并重新fopen()文件以进行读取。

By the time you call fgets() , the file pointer is already at end of file. 在您调用fgets() ,文件指针已位于文件末尾。 Add a call to rewind(fp) before your fgets() . 在您的fgets()之前添加一个调用rewind(fp)的调用。

Oh, also when you're opening the file, put your check for fp==NULL before the call to fprintf() . 哦,同样在打开文件时,请在调用fprintf()之前检查一下fp==NULL

There is easiest way to read from file and print on console. 有一种最简单的方法来读取文件并在控制台上打印。 use freopen() function to open file and read it using basic STD I/O. 使用freopen()函数打开文件并使用基本STD I / O读取文件。

I rewrite your solution in my way. 我用我的方式重写了您的解决方案。

 #include <stdio.h>

 int main()
 {
    char str[60];
    FILE* x = freopen("file.txt","r",stdin);
    if(x==NULL){
        printf("Error opening file");
        return(-1);
    }
    while(fgets (str, 60,stdin)){
        puts(str);
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM