[英]How to read large number of columns from file to arrays in C?
我想使用 C 從文件讀取大量(未知列數)到二維數組。 每行的列數是恆定的。 文件中的列由一個空格 (' ') 分隔。
我嘗試用循環內的循環來做,但沒有成功。 我還設法編寫了一個計算列數的代碼,但就我而言。 我是編程的初學者,所以任何幫助將不勝感激。
數據為txt格式,以空格分隔,每行偶數列。 我試圖將所有數據讀取到二維數組,因為我得出的結論是這種格式以后更容易使用。
我使用的代碼如下
int readData(char *filename, FILE *f) {
int lines;
int count = 0;
float dataArray [lines][count];
int i,j;
char c;
f = fopen(filename, "r");
if (f == NULL) return -1;
for (c = getc(f); c != '\n'; c = getc(f)) {
if (c == '\t')
count++;
}
printf("Your file %s consists of %d columns\n", filename, count);
printf("Set the lenght: ");
scanf("%d", &lines);
for(int i=0;i<lines;i++){
for(int j=0;j<count;j++){
fscanf(f,"%f", &dataArray[i][j]);
}
}
for (i=0; i<lines; i++) {
for (j=0;j<count;j++)c{
printf("%.3f",dataArray[i][j]);
}
printf("\n");
}
printf("\n");
fclose(f);
return 0;
}
int main (int argc, char *argv[], char filename[512]) {
FILE *f;
printf("Enter the file name: ");
if (scanf("%s", filename) != 1) {
printf("Error in the filename\n");
return -1;
}
if (readData(filename, f) == -1) {
printf("Error in file opening\n");
return -1;
}
return 0;
}
數據輸入是這樣的:
217,526 299,818 183,649 437,536 213,031 251 263,275 191,374 205,002 193,645 255,846 268,866 2,516\n
229,478 304,803 184,286 404,491 210,738 237,297 279,272 189,44 202,956 204,126 242,534 276,068 2,163\n
但是從中我得到了一個理想長度的數組,但是 rest 都是錯誤的,看起來像這樣:
225.0000000.000000-1798259351694660865572287994621067264.0000000.0000000.0000000.0000000.0000000.0000000.0000000.00000014037667868815752572174336.0000000.000000\n
225.0000000.000000-1798259351694660865572287994621067264.0000000.0000000.0000000.0000000.0000000.0000000.0000000.00000014037667868815752572174336.0000000.000000\n
您的目標陣列必須是動態的。 您正在使用未初始化的數據創建 static 數組:
float dataArray [lines][count]; // line is not initialized, and count = 0
將其更改為:
宣言:
float dataArray**;
初始化:
// only after setting count and lines
dataArray = malloc(lines * sizeof(float*));
for (int i = 0; i < lines; ++i) {
dataArray[i] = malloc(count * sizeof(float));
}
清理:當不再需要為dataArray
分配的 memory 時,您必須釋放它:
for (int i = 0; i < lines; ++i) {
free(dataArray[i]);
}
free(dataArray);
dataArray = NULL; // It's good to get used to nullify vars after deleting them
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.