【问题标题】:C cannot open text fileC 无法打开文本文件
【发布时间】:2012-08-21 04:13:52
【问题描述】:

我试图制作一个程序来告诉你一个文本文件中有多少个单词、行和字符,但是函数fopen() 无法打开文件。我尝试了文本文件的绝对路径和相对路径,但得到了相同的输出。你能告诉我有什么问题吗?

我的编译器是 gcc 版本 4.6.3 (Linux)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 256

void tokenize(const char *filename)
{
    FILE *f=NULL;
    char line[N],*p;
    unsigned long int ch=0,wd=0,ln=0;
    int t;
    f=fopen(filename,"rt");
    if(f==NULL)
    {
        perror("The following error occurred");
        exit(1);
    }
    fgets(line,N,f);
    while(!feof(f))
    {
        ln++;
        p=strtok(line," ");
        while(p!=NULL)
        {
            wd++;
            t=strlen(p);
            ch+=t;
            printf("Word number %lu with length %d: %s\n",wd,t,p);
            p=strtok(NULL," ");
        }
        fgets(line,N,f);
    }
    printf("%lu lines, %lu words, %lu characters\n",ln,wd,ch);
    fclose(f);
}

int main(void)
{
    char filename[80];
    size_t slen;
    printf("Enter filename path:\n");
    fgets(filename,80,stdin);
    slen = strlen (filename);
    if ((slen > 0) && (filename[slen-1] == '\n'))
         filename[slen-1] = '\0';
    printf("You have entered the following path: %s\n",filename);
    tokenize(filename);
    return 0;
}

输出:

Enter filename path:
input.txt
You have entered the following path: input.txt

The following error occurred: No such file or directory

【问题讨论】:

    标签: c file text-files token fopen


    【解决方案1】:

    您在文件名中保留了输入中的换行符。当您在输出中回显文件名时,您可以看到这一点:注意空白行。

    在将它传递给你的函数之前,你需要去掉这个换行符。有几种方法可以做到这一点,这里有一个:

    size_t idx = strlen(filename);
    if ((idx > 0) && filename[idx - 1] == '\n')
        filename[idx - 1] = '\0';
    

    【讨论】:

      【解决方案2】:

      您需要从字符串中删除尾随的换行符,例如:

      size_t slen = strlen (filename);
      if ((slen > 0) && (filename[slen-1] == '\n'))
          filename[slen-1] = '\0';
      

      而且,虽然我赞赏您使用 fgets 进行用户输入(因为它可以防止缓冲区溢出),但仍有一些边缘情况您没有考虑,例如当行太长时,或用户标记输入结束)。请参阅here 以获得更强大的解决方案。

      【讨论】:

        【解决方案3】:

        您可以声明如下函数:

        void rmnewline(char *s)
        {
        int l=strlen(s);
        if(l>0 && s[l-1]=='\n')
           s[l-1]='\0';
        }
        

        并在使用您的 char 数组之前调用它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-06
          相关资源
          最近更新 更多