我正在尝试将文本文件的每一行保存到一个数组中。 他们的方式我正在这样做并且到目前为止工作正常是这样的:
char *lines[40];
char line[50];
int i = 0 ;
char* eof ;
while( (eof = fgets(line, 50, in)) != NULL )
{
lines[i] = strdup(eof); /*Fills the array with line of the txt file one by one*/
i++;
}
我的文本文件有 40 行,我正在使用 for 循环访问它
for( j = 0; j <= 39 ; j++)
{ /*Do something to each line*/}.
到目前为止一切顺利。我的问题是我定义了数组 lines 的大小 对于具有 40 行的文本文件。我尝试计算行数然后定义大小,但我遇到了段错误。
我的方法:
int count=1 ; char c ;
for (c = getc(in); c != EOF; c = getc(in))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
printf("\nNUMBER OF LINES = %d \n",count);
char* lines[count];
有什么想法吗?
最佳答案
顺便说一句,我测试了你上面显示的确切代码以获得行数(通过计算换行符),在一个包含超过 1000 行的文件上,有些行 4000 个字符长。问题不在那里。 因此,seg 错误 可能是由于您为每个行缓冲区分配内存的方式所致。您可能试图将长行写入短缓冲区。 (也许我在您的帖子中遗漏了它,但找不到您解决行长的地方?)
在为文件中的字符串分配内存时,有两个有用的东西是行数和文件中的最大行长度。这些可用于创建 char
数组。
您可以通过在 fgets(...)
上循环来获得行数和最长行:(您主题的变体,本质上是让 fgets
找到换行符)
int countLines(FILE *fp, int *longest)
{
int i=0;
int max = 0;
char line[4095]; // max for C99 strings
*longest = max;
while(fgets(line, 4095, fp))
{
max = strlen(line);
if(max > *longest) *longest = max;//record longest
i++;//track line count
}
return i;
}
int main(void)
{
int longest;
char **strArr = {0};
FILE *fp = fopen("C:\\dev\\play\\text.txt", "r");
if(fp)
{
int count = countLines(fp, &longest);
printf("%d", count);
GetKey();
}
// use count and longest to create memory
strArr = create2D(strArr, count, longest);
if(strArr)
{
//use strArr ...
//free strArr
free2D(strArr, lines);
}
......and so on
return 0;
}
char ** create2D(char **a, int lines, int longest)
{
int i;
a = malloc(lines*sizeof(char *));
if(!a) return NULL;
{
for(i=0;i<lines;i++)
{
a[i] = malloc(longest+1);
if(!a[i]) return NULL;
}
}
return a;
}
void free2D(char **a, int lines)
{
int i;
for(i=0;i<lines;i++)
{
if(a[i]) free(a[i]);
}
if(a) free(a);
}
关于c - 将文本文件的每一行存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36801833/