Reputation: 21
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++;
}
}
Upvotes: 1
Views: 2029
Reputation: 426
#include <stdio.h>
int main()
{
char line[30];
char names[100][20];
int sizes[100];
int i = 0;
FILE *fp;
fp = fopen("1.txt", "rt");
if(fp == NULL)
{
printf("cannot open file\n");
return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
sscanf(line, "%[^,]", names[i]);//output the string until the char is the ","
sscanf(line, "%*s%s", sizes);//skip the characters and get the size of the file
printf("%s\n", names[i]);
printf("%s\n", sizes);
i++;
}
fclose(fp);
return 0;
}
i think this is what you want.
you should understand the sscanf() correctly.
Upvotes: 0
Reputation: 121971
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) {
Upvotes: 2