我在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