c - C中的ascii文件处理

标签 c file ascii

我很难理解你如何在 c 中处理 ascii 文件。我打开和关闭文件或读取每行一个值的文件都没有问题。但是,当数据用字符分隔时,我真的不明白代码在较低级别是做什么的。
示例:我有一个包含用逗号分隔的名称的文件,如下所示:"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER"我创建了一个数组来存储它们:char names[6000][20];现在,我处理它的代码是 while (fscanf(data, "\"%s\",", names[index]) != EOF) { index++; }代码在第一次迭代时执行,names[0] 包含整个文件。
如何将所有名称分开?
这是完整的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char names[6000][20]; // an array to store 6k names of max length 19
    FILE * data = fopen("./022names.txt", "r");
    int index = 0;
    int nbNames;

    while (fscanf(data, "\"%s\",", names[index]) != EOF) {
        index++;
    }

    nbNames = index;

    fclose(data);

    printf("%d\n", index);
    for (index=0; index<nbNames; index++) {
        printf("%s \n", names[index]);
    }
    printf("\n");

    return 0;
}
PS:我想这也可能是因为我的数组的数据结构。

最佳答案

如果您想要一个简单的解决方案,您可以使用 fgetc 逐个字符地读取文件。 .由于文件中没有换行符,只需忽略引号并在找到逗号时移至下一个索引。

char names[6000][20]; // an array to store 6k names of max length 19
FILE * data = fopen("./022names.txt", "r");
int name_count = 0, current_name_ind = 0;
int c;

while ((c = fgetc(data)) != EOF) {
    if (c == ',') {
        names[name_count][current_name_ind] = '\0';
        current_name_ind = 0;
        ++name_count;
    } else if (c != '"') {
        names[name_count][current_name_ind] = c;
        ++current_name_ind;
    }
}
names[name_count][current_name_ind] = '\0';

fclose(data);

关于c - C中的ascii文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66499608/

相关文章:

c - 如果不存在则创建虚拟表的替代方法

C 声明顺序错误

C语言前缀后缀问题

Python从自定义路径打开文件名

c++ - 将浮点值转换为 ascii 并再次转换回来,而不会引入错误

c - 将 Unicode 字符分配给 char

C 套接字 : FD_ISSET return true with no data waiting

c++ - 用 ofstream C++ 覆盖一行

java - 将数据从输入文件传输到输出文件,出现异常

bash - 如何从 linux 终端读取 8 位 ascii