The file that I am trying to read has the following contents:

192.168.1.1
48111
test.out
100
25

I am trying to use fscanf to read it line by line and storing each line in a variable. This works if I just have a couple of int variables, but it does not work for the above which also has an IP address and a file name. I tried saving the IP as a string but it just outputs garbage. Any suggestions?

Is the format of the input file pre defined or can it change
If the input file format is not fixed then this is a hard problem

Is the format of the input file pre defined or can it change
If the input file format is not fixed then this is a hard problem

The format is fixed and pre-defined. I just need to store the data in each line in different variables.

Dont use fscanf use fread .
Read the input into a char buffer . Then use string processing to extract the information you need

fscanf is a perfectly fine function to use for a configuration file with an absolute fixed format. I use it all the time. Wonderful function.

Here is an example which could be very relevant to you. This assumes linux. In windows, use the CR/LF combination.

This is the data structure.

typedef struct {
  char IP[16];
  int  Port;
  char FileName[255];
  int  Min, Max;
} DataStructure;

This is the code which performs the import. fscanf used properly makes the import extremely painless.

DataStructure Data;
FILE *f = fopen("connect.conf","r");

if (fscanf(f, "%s\n%d\n%s\n%d\n%d", Data.IP, &Data.Port, Data.FileName, &Data.Max, &Data.Min)!=5) {
  fprintf(stderr,"File not in correct format");
  return -1;
}

>> If the input file format is not fixed then this is a hard problem

Nothing is hard in C. If the file was not a fixed format, you just add a loop, int and switch.

wow thanks; that worked perfectly.

fscanf is a perfectly fine function to use for a configuration file with an absolute fixed format. I use it all the time. Wonderful function.

Here is an example which could be very relevant to you. This assumes linux. In windows, use the CR/LF combination.

This is the data structure.

typedef struct {
  char IP[16];
  int  Port;
  char FileName[255];
  int  Min, Max;
} DataStructure;

This is the code which performs the import. fscanf used properly makes the import extremely painless.

DataStructure Data;
FILE *f = fopen("connect.conf","r");

if (fscanf(f, "%s\n%d\n%s\n%d\n%d", Data.IP, &Data.Port, Data.FileName, &Data.Max, &Data.Min)!=5) {
  fprintf(stderr,"File not in correct format");
  return -1;
}

>> If the input file format is not fixed then this is a hard problem

Nothing is hard in C. If the file was not a fixed format, you just add a loop, int and switch.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.