Like Tree1Likes
  • 1 Post By anduril462

fread() and fwrite() - not working with gcc

This is a discussion on fread() and fwrite() - not working with gcc within the C Programming forums, part of the General Programming Boards category; Hello All, I am trying to use fread and fwrite in my program to be compiled using gcc. I searched ...

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    4

    Exclamation fread() and fwrite() - not working with gcc

    Hello All,
    I am trying to use fread and fwrite in my program to be compiled using gcc. I searched several forums but have no clue why neither of fread and fwrite work for me. Although no errors are shown and the fopen works well, reading or writing does not happen. Even a small code that i copied and pasted from a tutorials site on C-file I/O is not working!!

    Code:
    #include<stdio.h>
     
    int main()
    {
       FILE *f;
       int buf;
       f = fopen("aout.txt","wb");
       buf = 100;
       fwrite(&buf,sizeof(buf),1,f);
       fclose(f);
       return 0;
    }
    In the tutorials site, the output file extension was .dat, however since linux doesnt recognize that, i am using .txt. Is this allowed?
    Can anyone tell me what am i missing in the code or any package to be installed? I am using Ubuntu 11.04.

    Thanks
    anand

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    File extensions mean nothing. You can make your file called whatever you want. It's how you open the file that matters -- and actually, since you are in *nix, there is probably no difference between text and binary modes. It only matters how you read and write.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Quote Originally Posted by senartcon
    Although no errors are shown and the fopen works well, reading or writing does not happen.
    Check that fopen does not return a null pointer, and the return value of fwrite.

    Quote Originally Posted by senartcon
    In the tutorials site, the output file extension was .dat, however since linux doesnt recognize that, i am using .txt. Is this allowed?
    It is certainly allowed, but the notion that Linux does not recognise ".dat" is not quite right. You could have gone with ".dat" if you wished. The recognition of file extensions is by convention, so in that sense ".dat" is not recognised, but then it certainly is allowed.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Try running this code and then find your file "aout.txt" and open it. You will most likely see the letter 'A'.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
    
    	FILE *fp=NULL;
    	int x=65;
    
    	fp=fopen("aout.txt","wb");
    	if(!fp)
    		exit(1);
    
    	fwrite(&x,sizeof(x),1,fp);
    	fclose(fp);
    
    	return(0);
    }
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,487
    Minor addition to Andrew's code, that might produce some extra info that will help us:
    Code:
    fp = fopen("aout.txt", "wb");
    if (!fp) {
        perror("fopen failed");
        exit(1);
    }
    
    if (fwrite(&x, sizeof(x), 1, fp) != 1) {
        perror("fwrite failed");
    }
    AndrewHunter likes this.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,533
    The real question as to whether it worked or not is, do you see a 4 or 8 byte file when you do
    ls -l aout.txt
    at the command prompt?

    If you get No such file or directory, then it plainly did not work.

    Now if you try to open this ".txt" file in a text editor, you're not going to see "100", but probably just a 'd' (that being the ASCII character of decimal 100).

    If you want to see "100" in your .txt file, then use fprintf, not fwrite.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Mar 2009
    Posts
    344
    Quote Originally Posted by Salem View Post
    If you want to see "100" in your .txt file, then use fprintf, not fwrite.
    Or use
    Code:
    od -i aout.txt
    to display the file...

  8. #8
    Registered User
    Join Date
    Sep 2011
    Posts
    4
    Thanks all of you!

    AndrewHunter and anduril462 :

    I ran your code: got no errors and got "A" but only in emacs and could not open the result in gedit (text editor in ubuntu); gedit shows the following error:

    Could not revert the file /home.../aout.txt.
    Unexpected error: Invalid UTF-8 sequence in input


    The file size of aout.txt was 4 bytes

    Salem :
    yes, when i opened the result of my original code, buf=100; i got "d"
    and once again yes, the codes works well with printf and scanf (for any number of data points).
    However I was recommended that fread and fwrite are robust for "data" files.

    Talking of fread alone, in the code below, running at terminal i get the output:

    read one
    0.0000

    which looks like fread is reading but dont know whether it has read it properly!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
    
        FILE *fp1;
        float x;
    
        fp1 = fopen("ain", "rb");  //ain has a value 1.234 typed in
    
        if(fread(&x,sizeof(x),1,fp1)==1)
        printf("read one \n");
    
       printf("%f \n",x);
    
        fclose(fp1);
        return(0);
    }

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you just opened up a text file and typed in "1.234", then that's not going to correctly represent a float with fread. You should be using fscanf. Believe it or not, different IO methods have different functionality.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    Sep 2011
    Posts
    4
    Ok guys, here is the code working finally!!

    Code:
    #include <stdio.h>
    
    main(){
    
        FILE *fp1,*fp2;
        float y;
    
        fp1 = fopen("ain.txt", "rb");
        fp2 = fopen("aout.txt","wb");
        
        while(fread(&y,sizeof(y),1,fp1)==1)
        fwrite(&y,sizeof(y),1,fp2);
    
        fclose(fp1);
        fclose(fp2);
    }
    Inputs like this were outputted exactly the same way (in aout.txt)
    Code:
    1    1.2    1.23    1.234    1.2345
    2    2.3    2.34    2.345    2.3456
    3    3.4    3.45    3.456    3.4567
    4    4.5    4.56    4.567    4.5678
    5    5.6    5.67    5.678    5.6789
    6    6.7    6.78    6.789    6.79
    ....
    Now i have the following trouble:
    How do i get those numbers from aout.txt into the variables of structure elements? I tried with a little modification (code below), but it did not work.. I am getting random values. Any ideas, pls..!

    Code:
    #include <stdio.h>
    
    main()
    {
        FILE *fp;
        struct data {
            int x1;
            float x2;
            float x3;
            float x4;     
        } y[10];
    
        fp1 = fopen("aout.txt","rb");
    
        int i = 0;
        while(fread(&y[i],sizeof(y[i]),1,fp)==1)
        {
    printf("\n%d %f %f %f",y[i].x1,y[i].x2,y[i].x3,y[i].x4); i++;
    } printf("\n"); fclose(fp); }
    Thanks
    anand

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The first sample code does not produce the output you think you have produced (even if we ignore the whole text/binary difference, and assume you were showing us text as an illustration). You aren't writing line numbers or whatever that first column is. All you are doing is writing floating point numbers one after the other. There aren't any line breaks or anything.

    The only way your second program is going to work is if you are flat-writing full structures, the same way you wrote floats earlier. Is that what you meant by this:
    Quote Originally Posted by you
    Inputs like this were outputted exactly the same way (in aout.txt)
    If not, then you should do something like this:
    Code:
    while not done
        fread integer into array[ x ].int
        fread float into array[ x ].float1
        ...
        fread float into array[ x ].floatN
    If you wrote them out one at a time, and not as an entire structure, then you need to read them one at a time. If you wrote an entire structure at a time, then you need to read an entire structure at a time. (Assuming this file was written on the same machine it's being read on.)


    Quzah.
    Last edited by quzah; 09-23-2011 at 04:45 PM.
    Hope is the first step on the road to disappointment.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    1) you need to check the return from fopen() and make sure the file is *actually* open.
    2) You can't read text files with fread() ... that's for binary data.
    3) To read the file as text into floats you need fscanf()
    4) it's not main() ... it's int main (void)
    5) main() returns an errorlevel to the OS on exit... at minimum return 0;

    All of which you've already been told at least once before in this thread...
    What's the point of asking a question then ignoring the answers?

  13. #13
    Registered User
    Join Date
    Sep 2011
    Posts
    4
    Quote Originally Posted by CommonTater View Post
    1) you need to check the return from fopen() and make sure the file is *actually* open.
    2) You can't read text files with fread() ... that's for binary data.
    3) To read the file as text into floats you need fscanf()
    4) it's not main() ... it's int main (void)
    5) main() returns an errorlevel to the OS on exit... at minimum return 0;

    All of which you've already been told at least once before in this thread...
    What's the point of asking a question then ignoring the answers?
    SORRY for annoying you all guys. The above points are a real eye opener for me. I got it and i will shut up with fprintf and fscanf.
    Thanks to all...take care..

    anand

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fread() + fwrite() not working properly
    By TaiL in forum C Programming
    Replies: 13
    Last Post: 02-24-2010, 10:29 PM
  2. fread() & fwrite()
    By Roger in forum C Programming
    Replies: 2
    Last Post: 11-09-2009, 03:18 PM
  3. fread/fwrite
    By chopficaro in forum C Programming
    Replies: 6
    Last Post: 05-11-2008, 01:48 AM
  4. fwrite and fread help
    By jverkoey in forum C++ Programming
    Replies: 2
    Last Post: 02-12-2003, 09:17 PM
  5. fwrite() and fread()
    By Lau in forum C Programming
    Replies: 6
    Last Post: 12-05-2002, 09:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21