在C语言中,fgets
函数用于从指定的流中读取一行文本,而malloc
函数用于动态分配内存。结合使用这两个函数可以创建一个字符串数组,其中每个元素都是通过fgets
读取的字符串。以下是如何实现这一过程的详细步骤和示例代码:
malloc
可以根据需要动态分配内存,避免了静态数组大小固定的限制。以下是一个示例代码,展示了如何结合使用fgets
和malloc
来创建字符串数组:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *file;
char *line = NULL;
size_t len = 0;
ssize_t read;
int line_count = 0;
char **lines = NULL;
// 打开文件
file = fopen("input.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 逐行读取文件内容
while ((read = getline(&line, &len, file)) != -1) {
// 分配内存并复制读取的行
lines = realloc(lines, (line_count + 1) * sizeof(char *));
if (lines == NULL) {
perror("Error reallocating memory");
free(line);
fclose(file);
return 1;
}
lines[line_count] = malloc((read + 1) * sizeof(char));
if (lines[line_count] == NULL) {
perror("Error allocating memory");
free(line);
fclose(file);
return 1;
}
strncpy(lines[line_count], line, read);
lines[line_count][read] = '\0'; // 确保字符串以空字符结尾
line_count++;
}
// 关闭文件
fclose(file);
free(line);
// 打印读取的行
for (int i = 0; i < line_count; i++) {
printf("Line %d: %s\n", i + 1, lines[i]);
free(lines[i]); // 释放每行的内存
}
// 释放字符串数组的内存
free(lines);
return 0;
}
fopen
函数打开文件,并检查是否成功打开。getline
函数逐行读取文件内容。getline
会自动调整line
的大小以适应读取的行。realloc
调整字符串数组的大小,并使用malloc
为每一行分配内存。strncpy
将读取的行复制到新分配的内存中,并确保字符串以空字符结尾。getline
分配的内存。malloc
或realloc
返回NULL
,表示内存分配失败。应检查错误并进行适当的错误处理。fopen
返回NULL
,表示文件打开失败。应检查错误并进行适当的错误处理。通过这种方式,可以灵活地处理不确定数量的输入行,并有效地管理内存。
领取专属 10元无门槛券
手把手带您无忧上云