我试图将文件中的单词保留到数组中但我只读了前8个。
我的代码如下。
#define BUF 128 /* can change the buffer size as well */
char ** readFileContentArray(char* filename){
int lines = 128;
char ** strLines = (char **)malloc(sizeof(char*)*lines);
FILE *plist = NULL;
int i = 0;
char line[4];
plist = fopen(filename, "r");
while(fgets(line, BUF, plist)) {
if(i >= lines){
strLines = (char **)realloc(strLines, (lines*2) * sizeof(char *));
lines = lines*2;
}
strLines[i] = strdup(line);
i++;
}
return strLines;
}
我正在阅读的文件形成如下:
aaaa
bbbb
cccc
dddd
eeee
ffff
gggg
hhhh
iiii
JJJJ
答案 0 :(得分:3)
您可以将指针传递给两个整数,这样调用者就可以知道数组中分配了多少项
请致电char **strArray = readFileContentArray ( "file.txt", &total, &used);
结果可以打印
for ( i = 0; i < used; i++) {
printf ( "%s", strArray[i]);
}
同样免费&#39;
for ( i = 0; i < used; i++) {
free ( strArray[i]);
}
free ( strArry);
这些将在调用函数中使用。
char ** readFileContentArray(char* filename, int *lines, int *used){
*lines = 128;
*used = 0;
char **strLines = malloc(sizeof(char*)*(*lines));
char **strTemp = NULL;
FILE *plist = NULL;
char line[6];
plist = fopen(filename, "r");
if ( plist == NULL) {
return NULL;
}
while(fgets(line, sizeof ( line), plist)) {
if ( line[0] == '\n') {
continue;//blank line
}
if(*used >= *lines){
strTemp = realloc(strLines, ((*lines)*2) * sizeof(char *));
if ( strTemp == NULL) {
printf ( "realloc failed\n");
return strLines;
}
strLines = strTemp;
*lines = (*lines)*2;
}
strLines[*used] = strdup(line);
*used += 1;
}
return strLines;
}
答案 1 :(得分:2)
您的代码有几个问题。
malloc
/calloc
/realloc
in C fopen
是否成功。这可以通过检查其返回值来完成。失败时fopen
会返回NULL
。fgets
将128个字符写入line
,最多可容纳4个字符。固定代码:
#define BUF 128 /* Change to max size of a line */
char ** readFileContentArray(char* filename){
int lines = 128;
char ** strLines = malloc(sizeof(char*) * lines);
if(strLines == NULL) //If malloc failed
return NULL;
FILE *plist = NULL;
int i = 0;
char line[BUF]; //Allocate BUF size
if((plist = fopen(filename, "r")) == NULL) //If fopen failed
return NULL;
while(fgets(line, BUF, plist)) {
if(i >= lines){
char* temp;
if((temp = realloc(strLines, (lines*2) * sizeof(char *))) == NULL) //If realloc failed
{
free(strLines);
return NULL;
]
lines = lines*2;
}
strLines[i] = strdup(line);
i++;
}
fclose(plist); //Close file after its use
return realloc(strLines, i * sizeof(char*)); //Return correct size
}