【问题标题】:Why is the file not opening using fopen?为什么使用 fopen 打不开文件?
【发布时间】:2021-09-01 10:22:24
【问题描述】:

我尝试了几种方法,但都没有奏效。 我将txt文件复制到根文件中,它也没有打开。我也尝试使用 txt 文件的完整路径。当我尝试在另一台笔记本电脑上使用另一个 IDE 时,也发生了同样的事情。 编译器也没有给我任何错误。

这是我的代码:

int main()
{
    struct TreeNode *tmpDicNode;
    struct LinkedList *tmpLinkedList;

    FILE *infile;
    infile = fopen("..//Synonyms.txt" ,"r");
    char line[500];

    while(fgets(line, 500, infile))
    {
        //if ( strlen(line)>0){
            line[strlen(line) - 2] = '\0';

        char * token = strtok(line, " -\n");
        tmpDicNode = newTreeNode(token);
        tmpLinkedList = newLinkedList();

        while(token != NULL )
        {
            token = strtok(NULL, " , -\n");
            if (token != NULL)
            {
                insertSynonym(tmpLinkedList, token);
            }
        }
        tmpDicNode->synonyms = tmpLinkedList;
        Root = insertWord(Root, tmpDicNode);
    }

    fclose(infile);

    int ch = 0;
    char userWord[30];
    char userWord2[30];
    while(ch!=8)
    {
        printf("\n=====================================\n");
        printf("1. View The Dictionary.\n");
        printf("2. test word existence.\n3. print synonyms of a word.\n");
        printf("4. add a synonym to a word.\n5. get the biggest word with synonyms.\n");
        printf("6. get all words of a synonym.\n");
        printf("7. Save the dictionary to dict.txt file.\n");
        printf("8. Exit.\n");
        printf("=====================================\n");
        printf("\nEnter Your Choice: ");
        scanf("%d",&ch);
        switch (ch)
        {
        case 1:
            viewDictionary(Root);
            break;
        case 2:
            printf("Enter word: ");
            scanf("%s", userWord);
            if (findWordNode(userWord)) printf("%s is present in the dict \n", userWord);
            else printf("%s isn't found! \n", userWord);
            break;
        case 3:
            printf("Enter word: ");
            scanf("%s", userWord);
            printLinkedlist(findWordNode(userWord)->synonyms);
            break;
        case 4:
            printf("Enter word: ");
            scanf("%s", userWord);
            printf("Enter synonym: ");
            scanf("%s", userWord2);

            AddToWordSynonyms(userWord, userWord2);
            break;
        case 5:
            printf("The word with the height no. of Synonyms is: %s", getMaxSynsWord(Root)->word);
            break;
        case 6:
            printf("Enter a synonym: ");
            scanf("%s", userWord);
            getSyncWords(Root, userWord);
            break;
        case 7:
            saveTheDictToFile(Root);
            printf("The dictionary saved to others/dict.txt, Go and check it!\nGoodbye..!\n");
            ch = 8;
            break;
        case 8:
            printf("Goodbye..!\n");
            break;
        default:
            printf("Please Enter a valid option number from 1 to 7\n");
        }
    }

    return 0;

}

【问题讨论】:

  • fopen 返回NULL 时,您应该检查errno。 (顺便说一句,你有没有在"..//Synonyms.txt" 中添加一个额外的/?)
  • @Rinad Akl - mediocrevegetable 是正确的。 1) 您应该始终检查infile = fopen() 是否返回 0。这表示“fopen 失败”。 2) 检查errno 或致电perror() 找出失败的原因。 3) "..//Synonyms.txt" 几乎肯定是错误的。你的意思可能是"..\\Synonyms.txt"
  • 总是检查fopen的返回值。否则你不知道打开是否成功。以下也是不安全的:line[strlen(line) - 2] = '\0'; 如果strlen 返回01,你认为会发生什么?如果您曾经阅读过长行或未以 CRLF 序列结尾的行,这也会丢弃有用的字符。
  • 如果是 Windows 文件系统,则双(转义)斜线倾斜的方式错误。
  • 请注意,“..”是相对于运行程序的进程(shell或IDE)的当前目录,与程序所在目录无关。

标签: c file


【解决方案1】:

让我们在这里解决几个问题:

synonyms.txt

cold: cool,frigid,freezing
good: acceptable,virtuous

readsyn.c

/*
 * readsyn.c
 *
 * SAMPLE OUTPUT:
 *   Current directory: C:\Users\paulsm\workspace-cdt\readsyn\Debug
 *   Opening file (..\synonyms.txt)
 *   Reading file (..\synonyms.txt)
 *   line=cold: cool,frigid,freezing
 *   ...
 *   Currently 4 words
 *   line=good: acceptable,virtuous...
 *   Currently 7 words
 *   Done: found 2 lines
 *   synonyms[0]:cold synonyms[1]:cool synonyms[2]:frigid synonyms[3]:freezing synonyms[4]:good synonyms[5]:acceptable synonyms[6]:virtuous
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MAXWORDS 10
#define MAXLINE 80
#define TOKENS ":,"
#define FNAME "..\\synonyms.txt"

int main(int argc, char *argv[])
{
    char synonyms[MAXWORDS][MAXLINE] = {0};
    char current_folder[MAXLINE];
    char line[MAXLINE], *token;
    FILE *infile;
    int nlines = 0, iword=0;

    printf ("Current directory: %s\n", getcwd(current_folder, MAXLINE));

    printf ("Opening file (%s)\n", FNAME);
    if (!(infile = fopen(FNAME,"r"))) {
        perror("File open failed");
        return 1;
    }

    printf ("Reading file (%s)\n", FNAME);
    while((fgets(line, MAXLINE, infile) != NULL) && (iword < MAXWORDS))
    {
        printf("line=%s...\n", line);
        if (line[strlen(line)-1] == '\n')
            line[strlen(line)-1] = 0;
        token = strtok(line, TOKENS);
        while (token != NULL) {
            strncpy (synonyms[iword], token, MAXLINE);
            token = strtok(NULL, TOKENS);
            iword++;
        }
        printf("Currently %d words\n", iword);
        nlines++;
    }

    fclose(infile);
    printf ("Done: found %d lines\n", nlines);
    for (int i=0; i < iword; i++)
        printf ("synonyms[%d]:%s ", i, synonyms[i]);
    return 0;
}

要点:

  • 始终检查诸如“fopen()”之类的 I/O 操作是成功还是失败。
  • 您可以使用诸如 getcwd()(以及其他)之类的 API 来获取您当前的工作目录。
  • 如果 — 如您的示例 — 您没有为您的文件名,然后路径参数相对于应用程序的当前工作目录进行解释。在 Visual Studio 中,默认情况下隐藏在项目的 Debug 目录中;在 Linux 中,它将是您的 shell 的当前目录。

【讨论】:

  • 我编辑了关于绝对路径与相对路径的最后一部分,使其一目了然(我希望);如果您不喜欢它,请随时回滚。
  • @Peter - 谢谢 :) 我很想添加 a) 像 fopen() 这样的 API 接受 EITHER -nix 样式的正斜杠(“/”)以及 DOS/Windows 反斜杠(“\”)和b)反斜杠的问题在于它们都是escape character AND path delimiter.. . 但这会“有点多”;)
  • @Rinad Akl - 你被摆正了吗?
  • @paulm 你这是什么意思?我不得不查找表达式 (merriam-webster.com/dictionary/squared%20away) 但不能将其中一种含义应用于此上下文;-)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多