【问题标题】:Can we use two different methods to read a file in a same block of code?我们可以使用两种不同的方法在同一个代码块中读取文件吗?
【发布时间】:2023-03-24 16:19:01
【问题描述】:

// 我用来从文件中读取单词、字符、空格、换行符的方法.. // 但是当我运行它时,只有上面的 while 被执行,如果我首先放置下面的 whileloop, //只有那个被执行。简而言之,只有一个 while 循环被执行。 // 我该如何解决它??

#include<stdlib.h>
#include<string.h> 
int count_items(FILE *f);
// MAIN CODE
int main()
{ 
    printf("-------Programm to count_items in a file-------\n");

    FILE *f = fopen("sample.txt","r");

    count_items(f);

    fclose(f);

    return 0; 
} 

//FUNCTION TO COUNT NUMBER OF ITEMS IN A FILE

int count_items(FILE *f)
{
    int word_count,line_count,white_count,char_count;
    char sbuff[100],cbuff;

    // **Method I`m using to read characters from a file..**

    while((cbuff=getc(f))!=EOF)
    {
        char_count++;

        if(cbuff=='\n')
        {
            line_count++;
        }
        if(cbuff==' ')
        {
            white_count++;
            
        }

    } 

    while(fscanf(f,"%s",sbuff)==1)
    {
        word_count++;
    }

    // PRINT THE RESULT
    printf("The number of words in file are %d\n\n",word_count );
    printf("The number of characters in file are %d\n\n",char_count );
    printf("The number of whitespaces in file are %d\n\n",white_count );
    printf("The number of lines in file are %d\n\n",line_count );

    return 0;
} ```

// **IT SEEMS THAT I NEED TO FLUSH THE BUFFER BEFORE GOING TO SECOND WHILE LOOP. IF SO , HOW DO I DO THAT?**

【问题讨论】:

    标签: while-loop count scanf readfile getc


    【解决方案1】:

    我认为这是因为下一个循环试图从文件中读取,而当前位置位于该文件的末尾。您需要从头开始设置当前位置,例如

    fseek(f, SEEK_SET, 0);
    

    有关详细信息,请参阅fseek 规范。

    【讨论】:

    • 谢谢老哥,成功了。这个缓冲区问题是 C 中真正的颈部疼痛。Python 不是这种情况
    猜你喜欢
    • 2018-10-20
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2013-10-17
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多