使用fscanf在c中读取文件

时间:2013-08-27 21:57:54

标签: c file pointers

我参加了c编程课程,我有一个项目,他们给我们一个半成品项目,我们需要完成它并修复一些功能。 这个项目是关于某种社交网络。 在此项目中,您可以通过编写目标用户向其他用户(目前在同一台计算机上)发送消息,然后输入消息。之后,消息将保存在此格式的同一文件夹中名为“messages.txt”的文件中: “[At] 25/08/2013 [来自] user1 [To] user2 [留言]您好吗?” “[At] Date [From] user [To] user2 [Message]任何用户输入” 写完之后,我转到第二个用户并尝试使用此功能读取文件:

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 [Message]你好了吗?” 消息将是“你好” 它将被打印两次..我不知道该怎么办,由于某种原因,当我打开文件并执行fscanf一次时,它还显示指针文件启动“up?[At] ...(出现在第二行)“

如果你明白我做错了(我知道的很多),请帮助我 提前致谢

2 个答案:

答案 0 :(得分:1)

这部分fscanf:

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

只读一个单词“Hello what is up”,因为%s解析了连续的字符。

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

在文本消息中最多可读取80个字符,而不考虑空格等。此外,%80c的目标必须是80个字符或更多!

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

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

答案 1 :(得分:0)

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

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