c - C读取文件行到数组仅打印行中的第一个字符
问题描述
我尝试将 txt 文件中的行读取到 C 中的数组中。通过加载行的方法如下所示:
char *loadNames(FILE *file) {
char *list = malloc(42);
int BUFFER_SIZE = {256};
char *buffer = malloc(BUFFER_SIZE);
char count;
while (fgets(buffer, BUFFER_SIZE, file)) {
list[count] = *buffer;
count++;
}
return list;
}
稍后在我的代码中,我调用该函数并打印所有值。
char *names = loadNames(file);
for (int i = 0; i < 41; i++) {
printf("%c\n", names[i]);
}
该文件的每一行都包含一个名称。问题是当前代码只打印每个名称的第一个字符。
A
B
C
代替
Anna
Berry
Chanel
如果我在代码段#1 中打印buffer
while 语句中的值,则会显示全名。
我该怎么做才能获得全名而不是数组中的第一个字母?
解决方案
C 语言没有真正的字符串概念。但是标准库将字符串定义为空终止字符数组,其中char
是单字符类型。所以你想要的更接近:
#define BUFFER_SIZE 256
char *loadNames(FILE *file) {
char **list = malloc(42 * sizeof(char *)); // array of pointers
char buffer[BUFFER_SIZE];
char count = 0; // never forget initialization
while (fgets(buffer, BUFFER_SIZE, file)) {
list[count] = strdup(buffer); // allocate a new buffer
count++;
}
list[count] = NULL; // sentinel value
return list;
}
最后,您应该释放所有已分配的数组:
for(i=0; i<42; i++) {
if (list[i] == NULL) break; // stop at the sentinel
free(list[i]);
}
free(list);
推荐阅读
- prolog - 执行列表转换,Prolog
- python - 如何访问电子表格中的另一个页面?
- javascript - 车把问题
- android - 方法代码太大!android compileSdkVersion 27 更改为 compileSdkVersion 30 后
- angular - 在 NgRx 中,在哪里将来自服务器的响应数据(通过副作用获得)转换为组件可以理解的状态?
- python - 如何使用 python 将 UTC 时间转换为 UTC 中的相应日期和时间?
- python - 如何永远运行python代码直到停止它?
- javascript - 使用 Javascript 的文本框中的 Control+N 键事件
- email - SPF 记录不安全的配置
- c# - 无法在 Tizen.NET 可穿戴应用程序中向 tizen-manifest.xml 添加权限