我是C语言编程的新手,我的文件系统遇到了问题。该程序的目的是使用户输入一条消息,然后将该消息存储在文本文件中。用户的消息存储在文本文件中后,他们可以选择“阅读”他们所爱的人发送给他们的消息。
char SingleLine[150];
FILE * filePointer;
FILE * fpointer;
char mess[10];
char reply[100];
case 4:
printf("enter a message: ");
fscanf(stdin, "%s", mess);
filePointer = fopen("gift.txt", "w");
fprintf(filePointer, "%s \n", mess);
printf("you said %s \n", mess);
printf("they wrote something back?, would you like to read it? yes or no? \n ");
scanf("%s", &reply);
if ((toupper(reply[0]) == 'Y') && (toupper(reply[1]) == 'E') && (toupper(reply[2]) == 'S'))
{
printf("you said %s is that true???", &reply);
printf("ok loading...\n");
fpointer = fopen("luvtracey.txt", "r");
while (!feof(fpointer))
fgets(SingleLine, 150, fpointer);
puts(SingleLine);
}
else if ((toupper(reply[0]) == 'N') && (toupper(reply[1]) == 'O'))
{
printf("wow ignorant \n");
}
else
{
printf("your not having it anymore");
}
}
但是,当该代码首先运行时,当用户输入不带空格的消息时,它将被存储。但是,当您添加空格时,消息将被切成两半,并且第一位将被存储。其次,当您键入“是”时(当您想查看亲人发送的内容时),它完全崩溃了,但我不明白为什么。同样,它也不会检索其中包含单词的“ luvtracey.txt ”文件中的信息。
我接受反馈,我只想对那些帮助我解决这些问题的人表示感谢。
〜尼姆
if ((toupper(reply[0]) == 'Y') && (toupper(reply[1]) == 'E') ...
您可以将字符串转换为小写或大写和strcmp
,而不是一一检查字母。
while (!feof(fpointer))
fgets(SingleLine, 150, fpointer);
puts(SingleLine);
不要使用feof
。而是检查是否fgets
成功。大概您要打印文件中的每一行,因此不要在循环结束后打印该行。您还需要进行错误检查,以确保文件已成功打开。例:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char buffer[150];
printf("enter a message: ");
fscanf(stdin, "%s", buffer);
printf("you said %s \n", buffer);
FILE *fp = fopen("gift.txt", "w");
fprintf(fp, "%s \n", buffer);
fclose(fp);
printf("yes or no? ");
scanf("%s", buffer);
for(int i = 0, len = strlen(buffer); i < len; i++)
buffer[i] = (char)tolower(buffer[i]);
if (strcmp(buffer, "yes") == 0)
{
fp = fopen("luvtracey.txt", "r");
if(!fp)
{
printf("can't open...\n");
}
else
{
while(fgets(buffer, sizeof(buffer), fp))
printf("%s", buffer);
fclose(fp);
}
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句