【发布时间】: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"中添加一个额外的/?) -
总是检查
fopen的返回值。否则你不知道打开是否成功。以下也是不安全的:line[strlen(line) - 2] = '\0';如果strlen返回0或1,你认为会发生什么?如果您曾经阅读过长行或未以 CRLF 序列结尾的行,这也会丢弃有用的字符。 -
如果是 Windows 文件系统,则双(转义)斜线倾斜的方式错误。
-
请注意,“..”是相对于运行程序的进程(shell或IDE)的当前目录,与程序所在目录无关。