我正在学习 c 编程课程,我有这个项目,他们给了我们一个半成品的项目,我们需要完成它并修复一些功能。这个项目是关于某种社交网络的。在这个项目中,您可以通过编写目标用户向其他用户(目前在同一台计算机上)发送消息,然后输入消息。之后,消息以这种格式保存在同一文件夹中名为“messages.txt”的文件中:“[At]25/08/2013 [From]user1 [To]user2 [Message]hello whats up?” “[At]Date [From]user [To]user2 [Message]any user input”现在写完后,我转到第二个用户并尝试使用此功能从文件中读取:
void showUnreadMessages(char* userName) // the function gets the name of the current
user that wishes to read his/hers messages
{
char msg[MAX_MESSAGE];
char toU[MAX_USER_NAME];
char fromU[MAX_USER_NAME];
char at[15];
int count = 0, flag = 0, count1 = 0;
FILE *file = fopen(MESSAGE_FILENAME, "rt"); //open the messages file
FILE *temp;
clearScreen(); //system("CLS")
if (file == NULL) //if the file didn't exict open one
{
printf("No messages\n");
flag = 1;
_flushall();
file = fopen(MESSAGE_FILENAME, "wt");
_flushall();
}
while (!feof(file) && flag == 0) //if the file did exict
{
if (count1 == 0)
{
temp = file;
}
_flushall();
fscanf(file, "[At]%s [From]%s [To]%s [Message]%s\n", at, fromU, toU, msg); //scan one line at a time
_flushall();
if (strcmp(userName, toU) == 0) //if the userNames match than its a message for the current user
{
count++;
}
count1++;
}
fclose(file);
if (count > 0 && flag == 0) //if there are messages to user
{
printf("You have %d new Messages\n", count);
_flushall();
while (!feof(temp))
{
_flushall();
fscanf(temp, "[At]%s [From]%s [To]%s [Message]%s\n", at, fromU, toU, msg); //scan one line at a time to print it for the user
_flushall();
if (strcmp(userName, toU) == 0)
{
printf("New message at %s from: %s\nStart of message: %s\n-----------------------------------------\n", at, fromU, msg);
}
}
fclose(temp);
}
else if (count == 0 && flag == 0)
{
printf("You have no Messages\n");
}
if (!file)
{
remove(MESSAGE_FILENAME);
}
PAUSE; // system("PAUSE")
}
现在,当我尝试使用此功能阅读时,它仅显示该消息是第一行消息部分中的第一个单词......例如对于“[At]25/08/2013 [From]user1 [To] user2 [消息]你好,怎么了?” 该消息将是“你好”,它将被打印两次..我不知道该怎么做,由于某种原因,当我打开文件并执行一次 fscanf 时,它还显示指针文件开始“启动?[在] ...(出现在第二行的内容)”
如果您了解我做错了什么(我知道很多)请帮助我提前谢谢