Thread: file input/output

  1. #1
    Registered User
    Join Date
    Feb 2002

    Question file input/output

    trying to write a file with two user prompts i.e.
    int code & string title

    form this i wish to be able to read back the same information from the file. i can write the file however i cannot read back the file information one line at a time.


    0001 shriek
    0002 starwars

    can anyone help please........

  2. #2
    Join Date
    Aug 2001
    Groningen (NL)
    How did you open the file? I think you opened it as write-only, you should open it for read-write.

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Waterloo, Texas
    Place them in an array of structures to do it, opening the file in the binary read/write mode. Use fwrite and fread.
    Otherwise use a text file and open it in the standard read/write mode, and use fprintf and fscanf.

    this loop should work, for instance, on a text file, with an array of ints and strings:

    int code[size];
    char title[size][length];
    int x = 0;

    while(!foef(fp) && x++ < size)

    fscanf("%i %s", &code[x], &title[x]);
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
        return std::pow
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    An array of structs or even a linked list would work.
    struct data { char line[LEN]; } array[SIZE];
    struct data { int code; char title[LEN]; } array[SIZE];

    Read from the file until you don't have any more lines:
    while ( fgets( array[i].line, sizeof( struct data ), IN ) != NULL ) {
      /* Parse the line and process */
    while ( fread( array[i], sizeof( struct data ), 1, IN ) != 0 ) {
      /* Process each struct as you read it */
    Try to stay away from using feof() as your conditional for stopping the loop, you'll end up reading one line too many and the last struct will probably be garbage.

    Too tired, need sleep...

    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. File being filled with NULLs
    By Tigers! in forum Windows Programming
    Replies: 2
    Last Post: 06-30-2009, 05:28 PM
  3. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM