Samuel
Samuel

Reputation: 45

Error in reading string from file

I am having some trouble with reading a string from another file and storing it to an array. I need a pointer to point to that array so I can use it throughout the program. All variables are global. Please help fix the fgets lines to work with this. Thanks!

#include <stdio.h>
#include <stdlib.h>

void load_data();

int value;

char name[25];
char * nameP = NULL;

char another_name[25];
char * another_nameP = NULL;

int main()
{
   load_data();

   printf("value = %i\n", value);
   printf("name = %s\n", name);
   printf("another name = %s\n", another_name);

   return 0;
}
void load_data()
{
   FILE * fileP;

   if (!(fileP = fopen ("save_file.dat", "rt")))
   {
      printf("\nSave file \"save_file.dat\" not found.\n");
      printf("Make sure the file is located in the same folder as the executable file.\n\n");
      exit(1);
   }
   rewind(fileP);
   fscanf (fileP, "%i", &value);
   fgets (name, 25, fileP); // what is wrong with this line?
   fgets (another_name, 25, fileP); // what is wrong with this line?

   nameP = name;
   another_nameP = another_name;
} 

Contents of save_file.dat:

30
This is my name
This is another name

Upvotes: 0

Views: 150

Answers (1)

mfjones
mfjones

Reputation: 739

Is it perhaps because your fscanf doesn't include the \n character? Try:

fscanf(fileP, "%i\n", &value);

Since you don't read the new line character, your fgets (on the next line) simply continues reading until it finds either an EOF or \n. In this case, it instantly finds a \n character, so it stops reading. Hence, the 3rd line of your file is never being read.


In order to remove new lines at the end of fgets, simply add a function to do so:

void remove_newline(char *str) {
    size_t len = strlen(str);
    if (str[len-1] == '\n') {
        str[len-1] = '\0';
    }
}

Remember to #include <string.h>. Then, before printing out the data, simply call:

remove_newline(name);
/* ... */
printf("name = %s\n", name);

Upvotes: 1

Related Questions