0

I have a file and i need to read data from it. I have to read 2 int and 1 c string. This is my struct

typedef struct seats
{
int number, reserved;
char * name;
} seats;

This is my main

FILE *data;
seats input;
data = fopen("data.txt", "r+");
while(fscanf(data,"%s %d %d", input.name, &input.number, &input.reserved) != EOF)
{
    printf("%s %d %d", input.name, input.number, input.reserved);
}

Every time when i compile and run this software it crashes for some reason. Is there any solution?

3
  • What format is the data in? Is it text? Is it binary? Little-endian? Big-endian? Commented Jun 2, 2016 at 18:28
  • Does the tool you are using provide any sort of Logging system? If so, edit your question, and add relevant information such as the Tool, the language, the libraries used, etc. Otherwise we can only guess based on common mistakes. Please, read this (how to ask) and this (mcve) before asking, as those will help you get more and better answers from the community. Commented Jun 2, 2016 at 18:33
  • Its not login system, its simple assigment. Commented Jun 2, 2016 at 18:37

2 Answers 2

1

You haven't assigned any value to input.name, but you pass its garbage value to fscanf. You need to assign a variable a value before you attempt to use that value.

Sign up to request clarification or add additional context in comments.

3 Comments

when i added input.name="text" before i used it in fscanf it crashed also.
@NikolaButigan String literals are in read-only memory area (in modern OSes, with default compiler options), so setting input.name to point to string literal and then asking scanf to overwrite it will indeed cause segmentation fault.
@NikolaButigan Well that's even worse. Now you're passing fscanf a pointer to a constant and asking it to modify what that pointer points to.
0

Change your struct to something like this:

typedef struct seats{
    int number, reserved;
    char name[1000];
} seats;

and put a fflush(stdin), after printf(...)

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.