2013-08-27 110 views
0

我在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?[在] ...(第二行显示的内容)”

请帮助我,如果你明白我做错了什么(我知道是很多)提前 感谢

+0

'while(!feof())'几乎总是错的。 –

+0

'scanf'通常停止在空白处扫描。你可能想要选择一个更好的方法。 –

+0

scanf工作,其余我不知道 – jambono

回答

1

的fscanf的这一部分:

"..etc. [Message]%s\n" 

将只读取的一个字“喂什么事”,因为%S解析为连续的字符。

nr_fields = fscanf(file, "[At]%s [From]%s [To]%s [Message]%80c\n" 

最多可以读取80个字符,无论文本消息中是否有空格等。此外,%80c的目标地址必须为80个字符或更多!

此外,始终测试fscanf找到的字段数。

最后,fscanf在按照指示使用时有效,但确实有一些细微的方面。

0

一个问题是,temp是指向在第一次循环后调用fclose(file)后不再有效的句柄。您可以使用fgets()来读取一行,并使用strtok()strncpy()来分割读取的字符串。

我认为将阅读封装在一个额外的函数中以减少代码重复是一个好主意。