0

我试图制作一个程序,告诉您文本文件中有多少单词、行和字符,但该函数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
4

3 回答 3

4

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

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

size_t idx = strlen(filename);
if ((idx > 0) && filename[idx - 1] == '\n')
    filename[idx - 1] = '\0';
于 2012-08-21T04:15:44.160 回答
2

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

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

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

于 2012-08-21T04:22:15.847 回答
1

您可以声明一个函数,如:

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

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

于 2013-01-30T19:01:29.313 回答