问题描述
我很难理解您如何在c中处理ascii文件.我打开文件并关闭它们或读取每行一个值的文件没有问题.但是,当数据用字符分隔时,我真的不理解代码在较低级别上的作用.
I have a hard time understanding how you process ascii files in c. I have no problem opening files and closing them or reading files with one value on each line. However, when the data is separated with characters, I really don't understand what the code is doing at a lower level.
示例:我有一个文件,其中包含用逗号分隔的名称,如下所示:"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER"
Example: I have a file containing names separated with comas that looks like this:"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER"
我创建了一个数组来存储它们:字符名称[6000] [20];
现在,我要处理的代码是而(fscanf(data,``\ s''%s \'','',names [index])!= EOF){index ++;}
该代码将执行第一次迭代,名称[0]包含整个文件.
I have created an array to store them:char names[6000][20];
And now, my code to process it is while (fscanf(data, "\"%s\",", names[index]) != EOF) { index++; }
The code executes for the 1st iteration and names[0] contains the whole file.
如何分隔所有名称?
这是完整的代码:
#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:我认为这也可能是由于数组的数据结构所致.
PS: I am thinking this might also be because of the data structure of my array.
推荐答案
如果您想要一个简单的解决方案,则可以使用 fgetc
逐字符读取文件.由于文件中没有换行符,因此在找到逗号时,只需忽略引号并移至下一个索引.
If you want a simple solution, you can read the file character by character using fgetc
. Since there are no newlines in the file, just ignore quotation marks and move to the next index when you find a comma.
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语言处理ascii文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!