
[英]I having difficulty reading the file in my program. Am I using the for loop correctly to read the file?
[英]Am I using typedef structures and arrays correctly to read my file? It is not opening
我是 C 的数据结构初学者,我参加了 C 编程,但我在课程中只接触了一点结构,我没有跟上它。
无论如何,我正在尝试制作一个程序,它将数据从文件中读取到结构数组中,并打印出您填充的数组的内容。 我需要帮助来解决这个问题。老实说,我也不太确定我是否正确地这样做了......:/
非常感谢任何帮助,并提前感谢您::)
这是我到目前为止尝试过的
这是我的代码:
仅供参考 - 我要打开的文件是 DataFile.txt
#include<stdio.h>
#include <stdlib.h>
#define SIZE 10
#define ARRAY_SIZE 30
//Struct contains 3 fields, name, age, salary
typedef struct
{
char name[SIZE];
int age;
int salary;
} data;
data a[ARRAY_SIZE];
FILE * fp = fopen("DataFile.txt", "r");
if (fp == NULL)
{
printf("Error %s.\n", strerror(errno));
exit(1);
}
int GetData()
{
int i = 0;
fscanf(fp, "%s", a[i].name);
while(fp && i<ARRAY_SIZE)
{
fscanf(fp, "%d", &a[i].age);
fscanf(fp, "%d", &a[i].salary);
i++;
}
return i;
}
void ShowData( int records_read)
{
//Print text file data on screen
for(int i=0;i<records_read;i++)
{
printf("%s %d %d\n", a[i].name, a[i].age, a[i].salary);
}
}
int main()
{
char name[256];
int i = 0;
int records_read;
//Call the method, getData
i = GetData();
//Prompt and read input from the user
printf("Pick a number from 1 to 10:");
scanf("%d", &records_read);
//Call the method, showData
ShowData(records_read);
fclose(fp);
return 0;
}
如果我不把这部分代码放在:
FILE * fp = fopen("DataFile.txt", "r");
if (fp == NULL)
{
printf("Error %s.\n", strerror(errno));
exit(1);
}
但是 output 只是一个零列表..
快速回答:首先,尝试拆分FILE * fp = fopen("DataFile.txt", "r");
分为两部分,其中一个是变量声明FILE * fp = NULL;
另一个是赋值表达式fp = fopen("DataFile.txt", "r");
. 然后将变量声明的部分保留在所有函数之外,同时将赋值部分和 if 语句if (fp == NULL){...}
移动到 function GetData()
中。 在这种情况下,代码可能会起作用。
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.