我的程序运行正常,除了当我尝试读取输入的总数据时
#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);
}
我尝试仅读取文件,似乎从这样的文件中读取只能读取未用(空格键)或(输入)分隔的数据。 有办法解决这个问题吗?
答案 0 :(得分:2)
因此,您的代码中有2个问题。
result
没有分配内存。由于它是全局变量,因此将其初始化为0,也就是NULL指针。因此,您的scanf()看到了这一点,并且读取失败,printf()也是如此,并显示“(null)”。那里的解决方案是通过使其成为静态数组或使用malloc()在result
中分配内存。
即使您解决了第一个问题,也仍然无法按预期工作,因为fscanf()在遇到第一个空格后将停止读取输入。由于您希望读取整个(文件)输入,因此有四个选项:
要使用的功能是fgetc()
,getline()
,fread()
。此外,您可以按照this问题