Hi, I'm trying to program an application in C that will open a file do certain operations depending on what the line contains. For example, if it opened this file:
1 2 3 4 5
Do operation
Don't do operation
Do operation
Do operation
Don't do operation
The program should recognize that the first line is "Do operation" and do whatever operation. It would advance to the second line and recognize that it says "Don't do operation" so it wouldn't do any operation, and so on.
#include <stdio.h>
#define MAX_LINE_LEN 1000
int main()
{
FILE* f;
char line[ MAX_LINE_LEN ];
unsigned n = 0;
f = fopen( "trig.txt", "r" );
if (!f)
{
fprintf( stderr, "%s", "Could not open file \"trig.txt\".\n" );
return 1;
}
while (fgets( line, MAX_LINE_LEN, f ))
{
/* Do something with the line. For example: */
printf( "%03u: %s", ++n, line );
}
if (!feof( f ))
{
fprintf( stderr, "%s", "Hey, something went wrong when reading the file \"trig.txt\"!\n" );
fclose( f );
return 1;
}
puts( "Good-bye!\n" );
fclose( f );
return 0;
}
Long answer: A file is simply a sequence of characters. For example:
Once\nTwice\nThrice
A file can be considered as being read one character at a time. The fgets() function reads and stores characters until it reads a newline ('\n'), which it also stores.
before reading anything
Once\nTwice\nThrice
^next character to read
after reading the first line ("Once\n")
Once\nTwice\nThrice
^next character to read
after reading the second line ("Twice\n")
Once\nTwice\nThrice
^next character to read
etc
The caret represents the "file pointer", which tracks where in the file to read next. You can modify this by using the fseek() function, and you can learn where it is with the ftell() function.