#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    1
    Rep Power
    0

    Readind from file that is updated


    Hi
    I am new to C and I find it fascinating. I do some programming in Perl that is much easier than C.
    What I am trying to do in C is something very easy in Perl. I have a file that is constantly updated with data from GPS. I have script in C that read that file every second. The problem is that when I update that file while reading script is running I get "Segmentation fault (core dumped)" error. I did not have problem like this in Perl. How to solve it??

    Here is my simple file reading script:

    #include<stdio.h>
    int main()
    {
    char message[1000];
    FILE *file_in;
    while(1)
    {
    file_in=fopen("test.txt", "r");
    fscanf(file_in,"%s", message);
    printf("%s\n", message);
    fclose(file_in);
    }
    return 0;
    }

    Thanks in advance
    Robert
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,413
    Rep Power
    1871
    Step 1 is make sure you post code within [code][/code] tags, so that people can stomach reading the code.

    Step 2 is check for errors. Don't assume that the file was opened successfully.
    Code:
    file_in=fopen("test.txt", "r");
    if ( file_in ) {
        // do stuff
        fclose( file_in );
    } else {
        perror("Can't open file");
    }
    Step 3 - what is your input data format. If it's characters devoid of any white space at all, then %s will just overflow your buffer if you let it.
    It's safer to use fgets, like
    Code:
    file_in=fopen("test.txt", "r");
    if ( file_in ) {
        if ( fgets( message, sizeof(message), file_in ) != NULL ) {
            // do something with it
        }
        fclose( file_in );
    }
    Or more usually,
    Code:
        while ( fgets( message, sizeof(message), file_in ) != NULL ) {
            // do something with each line
        }
    Step 4, this will read from the beginning of the file each time. Do you perhaps want to read from where you got to last time?

    Step 5, use sleep() to allow more time for data to accumulate in the file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo