【问题标题】:Problem while opening a file because of weird characters on the file path由于文件路径上的奇怪字符,打开文件时出现问题
【发布时间】:2019-11-05 22:57:35
【问题描述】:

我正在从作为参数提供给我的应用程序的文件中读取某些文件的路径。 每条路径都写在一行上。我对给我这个错误的最后一条路径有疑问:

Cannot open C:\Users\Utente\Desktop\find\try1.txtl¹v

这是我的代码:

    struct filePath{
        char path[255];
        int fileOccurences;
    };

    struct filePath fPath[2];
    char currentLine[255];
    char path[255];
    char word[30];
    int i, ch;
    int k = 0;
    FILE * fInput = fopen(argv[1], "r"); 
    if(fInput == NULL){ //check sull'apertura del file
        fprintf(stderr, "Cannot open %s, exiting. . .\n", argv[1]);
       exit(1);
    }

    while(!feof(fInput)){
        for (i = 0; (i < (sizeof(path)-1) && ((ch = fgetc(fInput)) != EOF) && (ch != '\n')); i++){
            fPath[k].path[i] = ch;
        }
        FPath[k].path[i] = '\0';
        k = k + 1;
    }
    fclose(fInput);
    for(int j = 0; j<2; j++){
        FILE * fp = fopen(fPath[j].path, "r"); 
        if(fp == NULL){ 
            fprintf(stderr, "Cannot open %s, exiting. . .\n", fPath[j].path);
            exit(1);
        }
    }

我只上传了程序中感兴趣的部分,这不是我编写代码的确切方式。所以,有人知道我该如何解决这个问题并取消这些字符“l¹v”。谢谢。

【问题讨论】:

  • 你的程序运行得如何?你能举一个你在命令行上输入的例子吗?另外,您能否修复代码中的错误。我无法像在这个问题中那样编译和运行它,主要是因为你没有main()。
  • 此消息是因为fInput 为NULL 还是因为fp 为NULL?
  • 另外,更改错误消息。这样,我们就知道错误发生在哪里。
  • 您是否正在阅读while (!feof(Input)) 循环中的路径?不要那样做。stackoverflow.com/questions/5431941/…
  • 在错误信息中,不要只说“无法打开文件”。给出理由。 man perror 和 man strerror

标签: c file fopen


【解决方案1】:

您将文件名逐个字符地读入fPath[k].path[i],然后在循环后将path[i] 设置为nul。 但是fPath[k].path 和path 不是同一个变量,所以你没有空终止fPath[k].path[i]

【讨论】:

    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多