将每行文件读入数组

我正在读取一个文件,并希望将每一行放入一个数组中的字符串中。 文件的长度是任意的,每行的长度是任意的(虽然假设它将少于100个字符)。

这是我得到的,而不是编译。 基本上这是一个字符数组的数组,对吧? 所以不应该是char** words = (**char)malloc(sizeof(*char));

 #include  #include  int main(){ int BUFSIZE = 32767;//max number of lines to read char** words = (**char)malloc(sizeof(*char));//gives error: expected expression before 'char' FILE *fp = fopen("coll.txt", "r"); if (fp == 0){ fprintf(stderr, "Error opening file"); exit(1); } int i = 0; words[i] = malloc(BUFSIZE); while(fscanf(fp, "%100s", words[i]) == 1)//no line will be longer than 100 { i++; words[i] = realloc(words, sizeof(char*)*i); } int j; for(j = 0; j < i; j++) printf("%s\n", words); return 0; } 

注意:我读过“ 从文件中读取并存储在数组中 ”,但它没有回答我的问题。

您的计划存在一些问题。 realloc()语句未正确使用。 我也更喜欢fgets()来获取一条线。 这是我的解决方案。 这也使用realloc()来增加缓冲行的分配,这样你既不必事先知道行数,也不必两次读取文件(以这种方式更快)。 当您不知道需要提前分配多少内存时,这是一种常用的技术。

 #include  #include  int main(void) { int lines_allocated = 128; int max_line_len = 100; /* Allocate lines of text */ char **words = (char **)malloc(sizeof(char*)*lines_allocated); if (words==NULL) { fprintf(stderr,"Out of memory (1).\n"); exit(1); } FILE *fp = fopen("coll.txt", "r"); if (fp == NULL) { fprintf(stderr,"Error opening file.\n"); exit(2); } int i; for (i=0;1;i++) { int j; /* Have we gone over our line allocation? */ if (i >= lines_allocated) { int new_size; /* Double our allocation and re-allocate */ new_size = lines_allocated*2; words = (char **)realloc(words,sizeof(char*)*new_size); if (words==NULL) { fprintf(stderr,"Out of memory.\n"); exit(3); } lines_allocated = new_size; } /* Allocate space for the next line */ words[i] = malloc(max_line_len); if (words[i]==NULL) { fprintf(stderr,"Out of memory (3).\n"); exit(4); } if (fgets(words[i],max_line_len-1,fp)==NULL) break; /* Get rid of CR or LF at end of line */ for (j=strlen(words[i])-1;j>=0 && (words[i][j]=='\n' || words[i][j]=='\r');j--) ; words[i][j+1]='\0'; } /* Close file */ fclose(fp); int j; for(j = 0; j < i; j++) printf("%s\n", words[j]); /* Good practice to free memory */ for (;i>=0;i--) free(words[i]); free(words); return 0; } 

你应该改变这一行:

 char** words = (**char)malloc(sizeof(*char)); 

进入这个:

 char** words=(char **)malloc(sizeof(char *)*Max_Lines);