【发布时间】:2016-04-18 12:38:10
【问题描述】:
我正在尝试构建一个简单的函数,该函数将接收一个数据文件,并将数据文件中的各种值分配到一个全局结构数组中。但是,我无法让它正常工作。我已经编写了我认为大部分需要的代码,但我的测试行printf("time is %d\n", BP[i].time); 只是读出“时间为 0”。 10 次,让我相信这些值并没有像我想象的那样被分配给结构数组。
我该如何继续?
示例数据文件 (.txt):
0001 553 200
0002 552 100
.... ... ...
当前代码:
#include <stdio.h>
#include <stdlib.h>
// Function Prototype
void readFileBP(char fileName[1000]);
// Definition of BP Structure
struct bloodPressure
{
int *time;
int *sys;
int *dia;
}BP[50]; // end struct BP
int main()
{
char fileName[1000] = "C:\\Users\\User\\Desktop\\DataFiles\\BP_1.txt";
readFileBP(fileName);
int i = 0;
for (i; i<10; i++)
{
printf("Time is %d\n", BP[i].time);
}
} // end int main()
void readFileBP(char fileName[1000])
{
FILE *filePtr; // declare file pointer
int time;
int sys;
int dia;
int position = 0;
if (filePtr = fopen(fileName, "r") == NULL) // error check opening file
{
printf("Opening file failed. Please reenter filename.");
exit(1);
} // end if
while (fscanf(filePtr, "%d, %d, %d", &time, &sys, &dia) != EOF) // read in BP values
{
BP[position].time = time;
BP[position].sys = sys;
BP[position].dia = dia;
position++;
} // end while
fclose(filePtr);
} // end void readFile()
【问题讨论】:
-
现在是学习使用调试器的绝佳机会。逐步检查所有相关变量的代码以查看真正发生了什么! :-)
-
看这个
(filePtr = fopen(fileName, "r") == NULL)两次。这里发生了什么? -
作为最小的调试支持,您希望打印出在循环中读取的值inside。有什么被阅读的吗?
-
@alk 感谢您帮助识别违规行。正如你所说,我真的应该读出循环中的值。我是初学者,所以我不理解编译器向我抛出的大部分警告(例如
expecting an argument of type int but argument has type int *),但我设法看到错误的东西可能被分配给了filePtr。因此,我将开头移到 if 语句上方的一行。它不太干净,但我认为可以完成相同的工作!
标签: c if-statement struct file-management