![](/img/trans.png)
[英]How do I read data from a text file and store it in my C program to be used in functions?
[英]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);
}
我試着只做文件讀取,似乎像這樣從文件中讀取只能讀取不被(空格鍵)或(輸入)分隔的數據有沒有辦法解決這個問題?
所以你的代碼有兩個問題。
result
沒有分配給它的 memory。 由於它是一個全局變量,它被初始化為 0,也就是一個 NULL 指針。 因此,您的 scanf() 看到了這一點並且讀取失敗,printf() 也看到並打印“(null)”。 解決方案是通過使其成為 static 數組或使用 malloc() 在result
中分配 memory。
但是,即使您解決了第一個問題,它仍然無法按預期工作,因為 fscanf() 將在遇到第一個空格后停止讀取輸入。 由於您希望讀取整個(文件)輸入,因此您有四個選項:
要使用的函數是fgetc()
、 getline()
、 fread()
。 此外,您可以通過以下問題找到文件的大小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.