我在 C 中创建了这段代码来逐行读取文本文件并将每一行存储到数组的一个位置:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static const int MAX_NUMBER_OF_LINES = 100000;
static const char filename[] = "file.csv";
int main ( void )
{
// Read file and fill the Array
char *myArray[MAX_NUMBER_OF_LINES];
int numberLine = 0;
FILE *file = fopen (filename, "r");
if (file != NULL)
{
char line [128];
while (fgets (line, sizeof line, file) != NULL)
{
myArray[numberLine] = line;
numberLine++;
}
fclose (file);
}
// Print the Array
for (int i = 0; i<numberLine; i++)
{
printf("%d|%s", i, myArray[i]);
}
}
但是打印数组时,它是空的。我做错了什么?
因为您需要将行复制到数组的缓冲区中。
您需要为数组的每个元素中的字符串分配空间,然后使用类似strncpy
的方法将每个行
移动到每个myArray
插槽。
在您当前的代码中,您只是将相同的引用 - 复制到您的 line
缓冲区 - 到每个数组槽中,所以最后, myArray
的每个槽应该指向内存中的相同字符串。
根据 Shoaib 的建议,strdup 如果可用,将节省一个步骤,因此请尝试:
myArray[i] = strdup(line);
那里没有错误处理,请参阅 strncpy 的文档和 strdup .
或者,您可以向 myArray
添加一个维度:
char myArray[MAX_NUMBER_OF_LINES][100];
我是一名优秀的程序员,十分优秀!