Thread: file io

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    230

    file io

    hi i'm having two problems which i believe if i solve the first one the second will work(plus a little concern). i'm trying to write a program that opens a file(test.txt), and types Testing in it. at first it would give me an error when i ran it, i manually created the file and that solved the problem. now i'm trying to use fprintf to write to the file. but it won't work. i open the file after i run the program and its blank. because of that ofcourse i can't scan the file just to see whats inside it as a test. i'm trying two functions: fscanf and fgetc
    using fscanf:
    Code:
    /* File I/O
    */
    #include <stdio.h>
    int main() {
        FILE *test;
        char str[100];
        
        test = fopen("c:\\test.txt", "w+");
        fprintf(test, "Testing");
        fscanf(test, "%s", str);
        fclose(test);
        printf("str: %s", str);
        getchar();
        return 0;
    }
    and to use fgetc replace
    Code:
        fscanf(test, "%s", str);
    with
    Code:
    fgetc(str, 100, test)
    my to problems(summerized) are:
    1. why doesn't "w+" create the file?
    2. why isn't fprintf write to the file?
    my little concern is: getchar() is supposed to pause the program until i hit enter, why doesn't it work with some programs? like this one?

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    > 1. why doesn't "w+" create the file?

    It should be. According to the man page for fopen():
    w+ Open for reading and writing. The file is created
    if it does not exist, otherwise it is truncated.
    The stream is positioned at the beginning of the
    file.
    Maybe you should try some error checking. See if fopen() is returning NULL and if it is, see what errno is set to (you'll need to #include <errno.h> for that).

    > 2. why isn't fprintf write to the file?

    I think it probably is. The thing is, the stream pointer is at the pointer after where you just wrote Testing so your fscanf() is trying to read data that isn't there. Try putting rewind(test); between your fprintf() and fscanf() calls.
    If you understand what you're doing, you're not learning anything.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Between doing a 'write' to the file and doing a 'read', you have to do a fflush(test)

    You also need to do a fseek() as well, to get the position back to where you expect the data to start.
    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.

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    my little concern is: getchar() is supposed to pause the program until i hit enter, why doesn't it work with some programs? like this one?
    It doesn't work when there's already a character sitting in the input buffer (such as a newline from a scanf() call). So you probably didn't post the whole program? Anyway, to clear the input buffer, try this:
    Code:
    getchar()
    ->
    Code:
    int c;
    while((c = getchar()) != '\n' && c != EOF);
    http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    230
    i'm sorry after working on it for a looong while i found that dev-cpp is not compiling nor running the right file.
    Between doing a 'write' to the file and doing a 'read', you have to do a fflush(test)

    You also need to do a fseek() as well, to get the position back to where you expect the data to start.
    i remember writing and reading to the file without using any of the functions you mentioned. are they needed for simple strings?
    Quote:
    my little concern is: getchar() is supposed to pause the program until i hit enter, why doesn't it work with some programs? like this one?
    It doesn't work when there's already a character sitting in the input buffer (such as a newline from a scanf() call). So you probably didn't post the whole program? Anyway, to clear the input buffer, try this:
    actually i did post the full code. but what is the while loop for? how will it clear the input buffer?
    > 2. why isn't fprintf write to the file?

    I think it probably is. The thing is, the stream pointer is at the pointer after where you just wrote Testing so your fscanf() is trying to read data that isn't there. Try putting rewind(test); between your fprintf() and fscanf() calls.
    that problem would only happen if i'm trying to read the file using fscanf. i know i am but i'm also opening the file using notepad and it's just empty.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > are they needed for simple strings?
    Since files don't care about strings, I'd say yes it matters.

    Post your latest attempt if it's still not working for you.
    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.

  7. #7
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You still haven't shown that you're checking the return value of fopen() to see if it opened the file successfully...
    If you understand what you're doing, you're not learning anything.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    230
    i'm sorry i took long to reply as i was very busy studying. there was a problem(and until now there is). i created a new file(with same code) but its still not compiling it right. here's my new code
    Code:
    /* File I/O
    */
    #include <stdio.h>
    int main() {
       FILE *test;
       char str[100];
       
       test = fopen("c:\\test.txt", "w+");
       if(fopen("c:\\test.txt", "w+") != NULL) printf("File opened succesfully");
       else {
            printf("File could not be opened");
            /* i want to put a function here that exits the program */
       }
       fprintf(test, "Testing");
       fscanf(test, "%s", str);
       fclose(test);
       printf("str: %s", str);
       return 0;
    }
    does anyone see any problem with this code? is there a function that exits the program immediatly(does return work?) when i compile and run this code the program just starts and closes(even if i'm using cmd to see whats happened).
    Last edited by Abda92; 09-18-2006 at 09:35 AM.

  9. #9
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Yes. return 1; would work for exiting the program. It actually returns to the calling function, but since you're in main() it exits the program. The return value of 1 indicates to the calling program (the shell probably) that the program didn't finish successfully. If you weren't in main() and wanted to exit the program you could use the exit() function.

    I don't understand how the program isn't printing anything at all. You are calling fopen() twice though, which you shouldn't be doing. Just see if test is NULL after the initial fopen() call. The program should at least print whether or not the file was opened successfully. Try ending your printf() strings with a \n (e.g. "...successfully.\n")
    If you understand what you're doing, you're not learning anything.

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    230
    i tried it again with this code
    Code:
    /* File I/O
    */
    #include <stdio.h>
    int main() {
       FILE *test;
       char str[100];
       
       test = fopen("c:\\test.txt", "w+");
       if(test != NULL) printf("File opened succesfully\n");
       else {
            printf("File could not be opened");
            return 1;
       }
       fprintf(test, "Testing");
       fscanf(test, "%s", str);
       fclose(test);
       printf("str: %s", str);
       
       return 0;
    }
    and it printed "file opened succesfully". which means that there's something wrong with fprintf, i'm checking the file and it is empty. i tried deletintg the file and use "r+" mode and return 1 worked. thank you. now i just can't find out why the program is not working. can someone pleases try compiling it and running it? i would be very thankful.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    I still see no fseek or fflush calls.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        FILE *test;
        char str[100];
    
        test = fopen("test.txt", "w+");
        if (test != NULL) {
            printf("File opened succesfully\n");
        } else {
            printf("File could not be opened\n");
            exit(EXIT_FAILURE);
        }
        fprintf(test, "Testing");
        fflush(test);
        fseek(test, 1, SEEK_SET);   /* ignore first char */
        fscanf(test, "%s", str);
        fclose(test);
        printf("str: %s\n", str);
        return 0;
    }
    
    $ gcc new.c
    $ ./a.exe
    File opened succesfully
    str: esting
    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.

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    230
    i'll try putting them but i'm sure it worked without them.
    EDIT: it gives me an error when i do fseek(test): too few arguments. what arguments are there other than test?
    EDIT: sorry i did not read your code
    Last edited by Abda92; 09-18-2006 at 11:34 AM.

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    230
    thanks salem. i put fflush and it solved the writing problem somehow(how can it if it's after fprintf?). can you please explain your code(i see a lot of new lines)? and do i need stdlib.h?
    Last edited by Abda92; 09-18-2006 at 11:36 AM.

  14. #14
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Quote Originally Posted by Abda92
    and do i need stdlib.h?
    yes u need stdlib.h for the exit() function

    EDIT: I don't understand why the first char need to be ignored is that for the demonstartion purpose, Salem

    Code:
    fseek(test, 1 , SEEK_SET);
    ssharish2005
    Last edited by ssharish2005; 09-18-2006 at 12:59 PM.

  15. #15
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    No magic, just demonstrating.
    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.

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. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. File IO with .Net SDK and platform SDK
    By AtomRiot in forum Windows Programming
    Replies: 5
    Last Post: 12-14-2004, 10:18 AM