Sarah
Sarah

Reputation: 11

Segmentation error while reading from text file to a string in C

I'm kinda new to C programming ... I'm trying to read a user name from the user and another from a text file... the first one is working but when reading from the text file and storing into "user_name" it gives me a segmentation error. what's wrong here?

char user_in[10];
char user_name[10];
scanf("%s",user_in);
FILE *users_file;
users_file=fopen("users.txt","r");
fscanf(users_file,"%s",user_name);// segmentation error 

(EDITED) : The file does exist (I've tested it). the first content is a 5 character long string followed by a white space;

Sarah Mary Sally 

Upvotes: 0

Views: 253

Answers (3)

ObjectiveC-oder
ObjectiveC-oder

Reputation: 342

You'd be better giving a size in scanf()

scanf("%9s", user_in);

and

fscanf(users_file, "%9s", user_name);

You specify 9 as the length, since the final, tenth character has the value zero to represent the end of the string.

Also, as others have said, check that you successfully opened the file:

#include <errno.h>  /* errno */
#include <string.h> /* strerror() */


users_file = fopen("users.txt","r");
if(!users_file){
    fprintf(stderr, "couldn't open users.txt: %s\n", strerror(errno));
    return 1;
}

Upvotes: 0

Tony Bai
Tony Bai

Reputation: 151

the size of content which the program read from file is over the size of user_name. it would cause buffer overflow and break the function stack.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206636

You should ensure that you do not overwrite beyond the allocated array size of user_name.

You allocated user_name a memory of 10 characters, If your file contains more than the memory allocated for user_name then there is not enough space to store that content and it overwrittes the bounds of allocated memory causing an Undefined Behavior which can very well lead to a segmentation fault.

Also, there is no error handling in your program. For eg: You should be checking if the fopen call suceeded.
In short, whenever you use c standard library functions always check if the function was successful or not.

Upvotes: 1

Related Questions