簡體   English   中英

用fscanf在C中讀取文件

[英]File reading in c with fscanf

我上了c編程課程,我有一個項目,他們給了我們一個半成品項目,我們需要完成它並修復一些功能。 這個項目是關於某種社交網絡的。 在此項目中,您可以通過寫入目標用戶,然后將消息發送給其他用戶(目前在同一台計算機上),然后輸入消息。 之后,消息以以下格式保存在同一文件夾中的“ messages.txt”文件中:“ [At] 25/08/2013 [From] user1 [To] user2 [Message]您好嗎?” 編寫此代碼后,現在“ [在]日期[從]用戶[到] user2 [消息]任何用戶輸入”,我轉到第二個用戶並嘗試使用此功能從文件中讀取:

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 [消息]你好嗎? 該消息將是“ hello”,並且將被打印兩次。.我不知道該怎么辦,由於某種原因,當我打開文件並執行fscanf一次時,它還顯示指針文件開始“向上運行?[在]” ...(第二行顯示)”

如果您了解我做錯了什么(請問我知道很多),請幫助我。

fscanf的這一部分:

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

因為%s解析連續字符,所以只會讀一個單詞“ Hello what ups”。

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

最多可讀取80個字符,而無論短信中是否有空格。 另外,%80c的目的地必須是80個字符或更多!

另外,請始終測試fscanf找到的字段數。

最后,fscanf在按指示使用時可以正常工作,但是它確實具有一些微妙的方面。

一個問題是, temp指向的句柄在第一個循環后調用fclose(file)后不再有效。 您可以使用fgets()讀取一行,並使用strtok()strncpy()拆分讀取的字符串。

我認為將讀數封裝在一個額外的函數中以減少代碼重復是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM