如何解决我们可以使用两种不同的方法在同一代码块中读取文件吗?
// 我用来从文件中读取单词,字符,空格,换行符的方法。 // 但是,当我运行它时,只有上面的while被执行,如果我将下面的while循环放在首位, // 仅执行该操作。简而言之,只有一个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?**
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。