我正在尝试打开一个文件,逐行读取内容(不包括空行)并将所有这些行存储在一个数组中,但似乎我无法找到解决方案。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buffer[500];
FILE *fp;
int lineno = 0;
int n;
char topics[lineno];
if ((fp = fopen("abc.txt","r")) == NULL){
printf("Could not open abc.txt\n");
return(1);
}
while (!feof(fp))
{
// read in the line and make sure it was successful
if (fgets(buffer,500,fp) != NULL){
if(buffer[0] == '\n'){
}
else{
strncpy(topics[lineno],buffer, 50);
printf("%d: %s",lineno, topics[lineno]);
lineno++;
printf("%d: %s",lineno, buffer);
}
}
}
return(0);
}
考虑到“abc.txt”包含四行(第三行为空),如下所示:
AB
2
4
我一直在尝试几种方法,但我现在得到的只是分段错误。
答案 0 :(得分:2)
主要是因为您试图将读取线存储在 0长度数组
中int lineno = 0;
int n;
char topics[lineno]; //lineno is 0 here
在纠正上述问题后,您的程序会出现更多错误。
strncpy()
需要char*
作为其第一个参数,并且您传递char
。
如果你想以array[0]
是第一行的方式存储所有行,array[1]
是下一行,那么你需要一个`char数组指针。
像这样的东西
char* topics[100];
.
.
.
if (fgets(buffer,500,fp) != NULL){
if(buffer[0] == '\n'){
}
else{
topics[lineno] = malloc(128);
strncpy(topics[lineno],buffer, 50);
printf("%d: %s",lineno, topics[lineno]);
lineno++;
printf("%d: %s",lineno, buffer);
}
注意:强>
使用main()
int main(void) //if no command line arguments.
<强>加成强>
由于您不小心踏上 0长度数组,请阅读here。
答案 1 :(得分:1)
这个可变长度数组的声明
int lineno = 0;
char topics[lineno];
无效,因为数组的大小可能不等于0,并且在程序/
的上下文中没有意义您可以动态地将一个pojnters数组分配给类型为char *
的char,并在每次添加新记录时重新分配它。
例如
int lineno = 0;
int n;
char **topics = NULL;
//...
char **tmp = realloc( topics, ( lineno + 1 ) * sizeof( char * ) );
if ( tmp != NULL )
{
topics = tmp;
topics[lineno] = malloc( 50 * sizeof( char ) );
//... copy the string and so on
++lineno;
}