1

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++;
    }
}
2
  • 1
    possible duplicate of Reading a file line by line in C Commented Apr 29, 2012 at 22:06
  • 1
    Where is i declared/initialised? Commented Apr 29, 2012 at 22:10

2 Answers 2

2

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) {
Sign up to request clarification or add additional context in comments.

1 Comment

@IlanaMannine, what did you change?
0
#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.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.