簡體   English   中英

嘗試讀取文件中的信息(C編程)

[英]Trying to read information in a file (c programming)

我是C語言編程的新手,我的文件系統遇到了問題。 該程序的目的是使用戶輸入一條消息,然后將該消息存儲在文本文件中 用戶的消息存儲在文本文件中后,他們可以選擇“ 閱讀 ”他們所愛的人發送給他們的消息。

char SingleLine[150];
FILE * filePointer;
FILE * fpointer;
char mess[10];
char reply[100];

case 4:
    printf("enter a message: ");
    fscanf(stdin, "%s", mess);
    filePointer = fopen("gift.txt", "w");
    fprintf(filePointer, "%s \n", mess);
    printf("you said %s \n", mess);
    printf("they wrote something back?, would you like to read it?  yes or no? \n ");
    scanf("%s", &reply);    
    if ((toupper(reply[0]) == 'Y') && (toupper(reply[1]) == 'E') && (toupper(reply[2]) == 'S'))
    {
        printf("you said %s is that true???", &reply);
        printf("ok loading...\n");
        fpointer = fopen("luvtracey.txt", "r");
        while (!feof(fpointer))
            fgets(SingleLine, 150, fpointer);
            puts(SingleLine);
    }
    else if ((toupper(reply[0]) == 'N') && (toupper(reply[1]) == 'O'))
    {
        printf("wow ignorant \n");
    }
    else
    {
        printf("your not having it anymore");
    }
}

但是,當此代碼首先運行時,當用戶輸入 不帶空格的消息時,它將被存儲。 但是,當您添加空格時,消息將被成兩半,並且第一位將被存儲。 其次,當您鍵入“是”(當您想查看親人發送的內容時),它完全崩潰,但我不明白為什么。 同樣,它也不會檢索其中包含單詞的“ luvtracey.txt ”文件中的信息。

我接受反饋,我只想對那些幫助我解決這些問題的人表示感謝。

〜尼穆斯

if ((toupper(reply[0]) == 'Y') && (toupper(reply[1]) == 'E') ...

您可以將字符串轉換為小寫或大寫形式以及strcmp ,而不是一一檢查字母。

while (!feof(fpointer))
fgets(SingleLine, 150, fpointer);
puts(SingleLine);

不要使用feof 而是檢查fgets成功。 大概您要打印文件中的每一行,因此不要在循環結束后打印該行。 您還需要進行錯誤檢查,以確保文件已成功打開。 例:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    char buffer[150];
    printf("enter a message: ");
    fscanf(stdin, "%s", buffer);
    printf("you said %s \n", buffer);

    FILE *fp = fopen("gift.txt", "w");
    fprintf(fp, "%s \n", buffer);
    fclose(fp);

    printf("yes or no? ");
    scanf("%s", buffer);
    for(int i = 0, len = strlen(buffer); i < len; i++)
        buffer[i] = (char)tolower(buffer[i]);
    if (strcmp(buffer, "yes") == 0)
    {
        fp = fopen("luvtracey.txt", "r");
        if(!fp)
        {
            printf("can't open...\n");
        }
        else
        {
            while(fgets(buffer, sizeof(buffer), fp))
                printf("%s", buffer);
            fclose(fp);
        }
    }
    return 0;
}

暫無
暫無

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

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