我想处理txt文件中给出的数据。它有几行和两列。对于我的算法,我必须使用结构数组,以便每个数组项对应于txt文件中的一行。在一行内,有一个字符串和一个数字。因此,我创建了两个结构成员。我一行一行地填写结构。但是,不知何故,我必须将结构数组指针重置为第一个元素,这是我无法实现的。
#include <stdio.h>
void loadData(struct item *inputItems, FILE *inputStream);
void printItemStructure(struct item *itemArray, int nItems);
struct item{
char *tag;
double itemSize;
};
int main()
{
/* Handle the input file */
char *inputFileName = "d:\\Users\\User\\Downloads\\input.txt";
FILE *input;
input = fopen(inputFileName, "r");
if (input == NULL){
printf("Could not open the file for reading.");
return -1;
}
/* ========== Read the file content to the input structure ========== */
/*Determine the number of items by counting the rows of the input file */
int N = 0; /* number of items */
int nChars = -1; /* number of characters (exclude EOF character) */
char penChar; /* penultimate character */
char currentChar = ' '; /* last character read from the file stream */
char lastChar; /* number of characters */
while (!feof(input)){
lastChar = currentChar;
currentChar = fgetc(input);
nChars++;
if (currentChar == '\n')
N++;
}
if (lastChar != '\n' /* the file does not end with '\n' ... */
&& nChars != 0) /* ... and is not empty */
N++;
/* Process data row-by-row */
struct item *inputItems = calloc(N, sizeof(struct item));
struct item *origItems = inputItems; /* this will be reseted */
loadData(inputItems, input);
inputItems = origItems;
printItemStructure(inputItems, N);
/* Close the file */
fclose(input);
return 0;
}
void loadData(struct item *inputItems, FILE *inputStream){
rewind(inputStream);
char *start = inputItems[0].tag;
char row[200];
int rowSize = 200;
int i = 0;
char title[200];
double size;
while (fgets(row, rowSize, inputStream)){
sscanf(row, "%s %lf", title, &size); // why doesn't it work directly?
inputItems[i].tag = title;
inputItems[i].itemSize = size;
printf("%s\n", row);
i++;
}
}
void printItemStructure(struct item *itemArray, int nItems){
/* Print the members of the item structure array for debugging purposes */
for (int j = 0; j<nItems; j++)
{
printf("\nitemArray[%d]\n Tag: %s, Size: %lf\n",
j, itemArray[j].tag, itemArray[j].itemSize);
}
}
为什么我无法重置*tag
结构数组的inputItems
字段?
input.txt
文件包含:
Film1 1.8
Film2 4.25