[C] Reading data from file per line

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.

So far, this is what my program looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *input = NULL;
    int size;

    FILE *trig = fopen("trig.txt", "r");
    if(trig == NULL)
        return 1;

    fseek(trig, 0, SEEK_END);
    size = ftell(trig);
    rewind(trig);

    input = malloc(size);

    fread(input, 1, size, trig);

    //code that parses each line

    fclose(trig);

    return 0;
}


I know of the fgets function and it will retrieve a string for the first line, but I'm unaware of how to get the second line and the rest.

Any help is appreciated.
Call fgets() once for each line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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;
  }

Hope this helps.
So is it okay to assume that fgets will adjust the position to the next line after calling it?
Short answer: Yes.

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.

Hope this helps.
Topic archived. No new replies allowed.