我在c编程中学习了一个类,我有这个项目,他们给了我们一个半制作的项目,我们需要完成它并修复一些函数。 这个项目是关于某种社交网络。 在此项目中,您可以通过编写目标用户,然后输入消息,将消息发送给其他用户(现在在同一台计算机上)。之后,邮件将保存在以下格式的同一文件夹中的“messages.txt”文件中: “[At] 25/08/2013 [From] user1 [To] user2 [Message] hello whats up? “[在]日期[从]用户[转] USER2 [信息]任何用户输入” 现在写这之后,我去了第二个用户,并尝试从文件中使用此功能阅读:用fscanf在c中读取文件
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 [到] user2 [消息]你好,怎么了? 消息将是“你好” 它将被打印两次..我不知道该怎么办,出于某种原因,当我打开文件并执行fscanf一次它也显示指针文件开始“up?[在] ...(第二行显示的内容)”
请帮助我,如果你明白我做错了什么(我知道是很多)提前 感谢
'while(!feof())'几乎总是错的。 –
'scanf'通常停止在空白处扫描。你可能想要选择一个更好的方法。 –
scanf工作,其余我不知道 – jambono