Thread: Reading from a file and using the data

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    3

    Reading from a file and using the data

    Hello all,

    I am looking to keep a file with the running log the highest serial number issues, and therefore i know the next one to issue.

    I have loaded the file by:

    Code:
    FILE *fp;
    if ((fp = fopen("programdata", "r")) ==NULL){
    printf("Error Data opening file\n");
     system("pause");
    }
    
    else { printf("Data file opened successfully\n");
    system("pause");
    }
    it seems to load the file ok, but now i would like to read the data out of the file (it will be an int number)

    i have tried:
    Code:
    int fgetc(FILE *fp); //load in highest saved serial number
    
    int fclose(FILE *fp);
    printf("Data Loaded\n");
    system("pause");
    this will give me avalible data (currently a value of "4") but how do i put it into a global variable so i can access it?

    Thanks...

    Steve

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Perhaps what you want to use is fgets()?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    3
    does this mean i can go:

    Code:
    int variablename;
    variablename = fgets(FILE *fp);
    printf("variablename");
    will this print out the first value in my file?

    How will i go about loading extra data from a file, for instance if i have a .txt file that looks like:

    Code:
    1 steve 23 engineer
    2 bob 32 plumber
    can i still use fgets()?

    sorry to be asking such basic questions, but i havn't programmed C for years now, and it is true that if you don't use it you lose it!

    Any good links on file handling, reading and writing?

    Ste

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    No, not really. Since you indicated fgetc() I was thinking you wanted to read a text-string, not an integer value. If you want to read an integer value from a text-file, then fscanf() is probably the right thing to do.

    For your second problem, either fscanf() or fgets() would work.

    fgets takes three parameters:
    1. a buffer to store a string in.
    2. the size of the buffer.
    3. the file to read from (which can be stdin if you want to read directly from console input).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed