Problem with fgets function
I have a file foo.txt with 2 lines. I want to retrieve each of them in variables for use in the main code.
Code:
void reading_file()
{
char *name = "foo.txt";
char line [BUFSIZ];
FILE *file = fopen (name, "r");
if (file != NULL)
{
while (fgets (line, sizeof line, file) != NULL)
{
printf("%s", line);
}
fclose (file);
}
else
{
perror ("Impossible to open the file.");
}
}
Re: Problem with fgets function
If you want to use your variables in the main code you have to create storage space for your lines with a malloc.
Then (if you do not know the number of variables lines refer to the main code) you must do a dynamic sort a linked list that contains:
- A pointer to the malloc that contains your credit line
- A pointer to the next cell containing the next cell
For code I had think there's not too far already for a moment, I tried to find it in the evening if necessary.
Re: Problem with fgets function
My first line is set to 4 bytes. The second is an integer between 1 and 1000. I want to code if it is not too much a constraint. I used this piece of code using the function scanf that works and meets my needs but I do not know if this is optimal.
Code:
void reading_file()
{
char *name = "foo.txt";
char value1[4];
char value2[BUFSIZ];
FILE *file;
if ((file = fopen (name, "r")) == NULL)
perror ("Impossible to open the file.");
else
{
while ( fscanf ( file, "%s %s", value1, value2 ) == 2)
printf("%s\n%s\n", value1, value2);
fclose (file);
}
}
The problem is when I try to do a comparison test between value1 and an integer, I have this error message:
Attention: Comparison between a pointer and an integer
Re: Problem with fgets function
This is normal: value1 is a pointer to an array of 4 characters.