你如何分割从一个文件读入C数组字符串 [英] How do you split a string read from a file into arrays in C
问题描述
我有了100文件名及其相应大小的像这样的列表一个简单的文件:
FILE1.TXT,4000
FILE2.TXT,5000
等。
我如何逐行读取文件中的行,然后文件名列表尺寸列表保存到一个字符数组,然后到一个int数组?我想使用的sscanf这样的,但是这是行不通的。我得到一个赛格故障:
的main(){
焦线[30];
炭名称[100] [20];
INT尺寸[100];
FILE * FP;
FP = FOPEN(Filelist.txt中,RT);
如果(FP == NULL){
的printf(无法打开Filelist.txt中\\ n);
返回;
} 而(与fgets(线,的sizeof(线),FP)!= NULL){
sscanf的(行,%s和%D,名称由[i] [0],大小[I]);
的printf(%D,大小[I]);
我++;
}
}
I
不是来自超过pvented $ P $ 100
,这是和名称
可读取尺寸的最大数量。如果在文件中一百多线就会产生出界访问。通过本(或类似)的变化prevent这样的:
而(I< 100安培;!与fgets(行,sizeof的(线),FP)= NULL){
I have a simple file that has a list of 100 file names and their corresponding sizes like this:
file1.txt, 4000
file2.txt, 5000
etc.. How do I read the file line by line and then store the list of filenames into a char array and then the list of sizes into an int array? I am trying to use sscanf like this but this is not working. I am getting a seg fault:
main(){
char line[30];
char names[100][20];
int sizes[100];
FILE *fp;
fp = fopen("filelist.txt", "rt");
if(fp == NULL){
printf("Cannot open filelist.txt\n");
return;
}
while(fgets(line, sizeof(line), fp) != NULL){
sscanf(line, "%s, %d", names[i][0], sizes[i]);
printf("%d", sizes[i]);
i++;
}
}
i
is not prevented from exceeding 100
, which is the maximum number of sizes
and names
that can be read. If there are more than one hundred lines in the file then an out of bounds access will occur. Prevent this by making this (or similar) change:
while (i < 100 & fgets(line, sizeof(line), fp) != NULL) {
这篇关于你如何分割从一个文件读入C数组字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!