簡體   English   中英

為什么我的程序無法從我的文件中讀取數據

[英]Why is My Program Unable To Read the Data from My File

我的程序主要工作,除了當我嘗試讀取輸入的總數據時

#include <stdio.h>
#include <string.h>
#define bufferSize 300
char name[50], gift[50], list[300], end[50], *result;
int i;
int main()
{
    FILE *appendPlace = fopen("NamesAndGifts.txt", "a");
    FILE *readData = fopen("NamesAndGifts.txt", "r"); //my place for reading data
    printf("This is a Gift Entering System for 3 People Only\nThe Name of the Person then their Gift Description will be taken\nThe Gift Description is Basically the Gift Name");
    while (strcmp(end, "END") != 0) {
        printf("\nEnter Name of Person %d or type 'END' to Exit Sequence\n", i + 1);
        scanf("%s", &end);
        if (strcmp(end, "END") != 0) {
            strcpy(name, end);
            printf("Now Enter Gift Description (Gift Name) of Person %d\n", i + 1);
            scanf("%s", &gift);
            strcat(list, "\n");
            strcat(list, "Name: ");
            strcat(list, name);
            strcat(list, "\n");
            strcat(list, "Gift: ");
            strcat(list, gift);
            strcat(list, "\n");
        }
        i++;
    }
    printf("The Gift Entering System (Names and their respective Gifts) is Below:\n");
    printf("%s", list);

    fputs(list, appendPlace);
    fclose(appendPlace);
    //below I attempt to read file Data to be able to print file's Data into running program
    fscanf(readData, "%s", result);
    printf("\n\n\n\n\n\n\nTotal Data in File Below:\n%s", result);
    fclose(readData);
}

我試着只做文件讀取,似乎像這樣從文件中讀取只能讀取不被(空格鍵)或(輸入)分隔的數據有沒有辦法解決這個問題?

所以你的代碼有兩個問題。

  1. result沒有分配給它的 memory。 由於它是一個全局變量,它被初始化為 0,也就是一個 NULL 指針。 因此,您的 scanf() 看到了這一點並且讀取失敗,printf() 也看到並打印“(null)”。 解決方案是通過使其成為 static 數組或使用 malloc() 在result中分配 memory。

  2. 但是,即使您解決了第一個問題,它仍然無法按預期工作,因為 fscanf() 將在遇到第一個空格后停止讀取輸入。 由於您希望讀取整個(文件)輸入,因此您有四個選項:

    • 逐個字符讀取(出於性能原因不建議這樣做,但可能是最容易實現的)
    • 逐行閱讀(相當標准的方式)
    • 給定一些預先分配的緩沖區或逐塊讀取塊
    • 一次讀取整個文件(不建議用於大文件)

要使用的函數是fgetc()getline()fread() 此外,您可以通過以下問題找到文件的大小

暫無
暫無

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

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