我正在尝试创建一个函数 read_lines,它接受一个文件 *fp、一个指向 char** 行的指针和一个指向 int num_lines 的指针。该函数应将每一行文本插入多行,并将 num_lines 增加到文件中的任意行数。
它可能真的很简单,但我已经尝试插入文本几个小时了。
这就是 main.c 的样子。除了 read_lines 之外的所有内容都已经定义并且可以工作。该文件可以有任意数量的行、制表符,甚至可以只有换行符。
(这是一个家庭作业,所以 main.c 和函数声明必须保持不变)
int main(int argc, char* argv[]){
char** lines = NULL;
int num_lines = 0;
FILE* fp = validate_input(argc, argv);
read_lines(fp, &lines, &num_lines);
print_lines(lines, num_lines);
free_lines(lines, num_lines);
fclose(fp);
return 0;
}
这是我尝试附加行的尝试之一,但我无法弄明白。
read_lines.c
void read_lines(FILE *fp, char ***lines, int *num_lines) {
int i;
int N = 0;
char s[200];
for (i=0; i<3; i++)
{
while(fgets(s, 200, fp)!=NULL){N++;}
char strings[50][200];
rewind(fp);
fgets(s, 200, fp);
strcpy(lines[i],s);
}
}
如果能帮我解决这个问题,我将不胜感激。
最佳答案
您需要在读取每一行时动态分配内存。这是通过 malloc 完成的和 realloc功能。 malloc
分配内存,realloc
调整分配大小。
下面的代码应该做你想做的(我没有广泛测试它),但省略了错误检查,这将是一个很好的做法。
void read_lines (FILE *fp, char ***lines, int *num_lines) {
// Initialize you number of lines variable
*num_lines = 0;
//Initialize the lines pointer
// NO ERROR CHECKING DONE HERE
*lines = malloc(sizeof(char*));
// create a fixed size buffer for reading from file
char s[200];
// Read from the file using fgets
while (fgets(s, 200, fp) != NULL) {
// THIS CODE ASSUMES ALL LINES ARE LESS THAN 200 CHARACTERS
// The memory to hold the line of text needs to be allocated
int length = strlen(s);
// Ensure there is space for the terminating null character
(*lines)[*num_lines] = malloc(sizeof(char) * (length + 1));
// The line needs to be copied from the buffer to the allocated memory
strcpy((*lines)[*num_lines], s);
// increment number of lines variable
*num_lines++;
// allocate space for another line in advance
*lines = realloc(*lines, sizeof(char*) * ((*num_lines) + 1));
}
// There will be an extra line pointer allocated in the loop
// Shrink the allocation to the appropriate size
*lines = realloc(*lines, sizeof(char*) * (*num_lines));
}
关于c - readlines 函数将文件中的文本逐行插入到指针传递的字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56420235/