【问题标题】:reading characters from a file using c code使用c代码从文件中读取字符
【发布时间】:2014-04-13 13:20:18
【问题描述】:

我编写了一个 C 代码来计算文件中的字符、单词和行数。
代码如下。

#include "stdio.h"
#include "conio.h"

#define FILE_NAME "abc.txt"

void main()
{
    FILE *fr;
    int noc = 0;
    int now = 0;
    int nol = 0;
    char ch;

    printf("hello world\n");
    getch();

    //clrscr();

    fr = fopen("..\\abc.txt","r");

    if(fr == NULL)
    {
        printf("\n error \n");
        getch();
        return;
    }

    ch = fgetc(fr);
    while(ch != EOF)
    {
        printf("%c", ch);
        noc++;
        if(ch == ' ');
        {
            now++;
        }
        if(ch=='\n')
        {
            nol++;
            now++;
        }
        ch=fgetc(fr);
    }

    fclose(fr);

    printf("\n noc = %d now = %d nol = %d\n", noc, now, nol);
    getch();
}

我的文件 abc.txt 如下。

Hello my friend. 
How are you doing? 

我得到以下输出:

hello world
Hello my friend.
How are you doing?

 noc = 38 now = 40 nol = 2

代码能够正确读取字符数和行数。但是,它将每个字符视为一个单词。在计算上面代码中的单词时,我不明白我哪里出错了。

详细解释将不胜感激。
提前致谢。

【问题讨论】:

  • char ch 永远不会是 EOF,因为 EOF 是一个整数常量。如果要使用fgetc() 查找EOF,请将ch 定义为int。请注意char,因为它是由实现定义的,是否已签名。

标签: c character-encoding char character


【解决方案1】:
if(ch == ' '); <------- see this (remove semicolon)
{
     now++;
}

【讨论】:

  • @Jay 你的程序很好而且很容易练习,但我希望你知道如果你的文件中的单词使用了多个空格或标签空间在它们之间。
  • 是的.. 我已经为此添加了这个: if((prevch != ' ' && prevch != '\t' && prevch != '\n') && (ch == ' ' || ch == '\t' || ch=='\n'))
  • @Jay:您可以通过isblank(char) 测试空格('\t' 或' ')字符,或通过!isprint(char) 测试不可打印字符,或非图形字符!isgraph(char) 一口气。
  • @jay EOF 是对的,而且我认为if((prevch != ' ' &amp;&amp; prevch != '\t' &amp;&amp; prevch != '\n') &amp;&amp; (ch == ' ' || ch == '\t' || ch=='\n')) 在更容易出错的情况下(如果空间多于 2 个或 3 个或 5 个怎么办)对您没有多大帮助,你应该尝试跳过文件中单词之间可能出现的任何空白字符。有关实现,请参阅this 帖子。
  • 感谢大家的宝贵意见。真的很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 2012-02-04
  • 2017-09-06
  • 1970-01-01
相关资源
最近更新 更多