fread, fwrite

This is a discussion on fread, fwrite within the C Programming forums, part of the General Programming Boards category; Hello I am trying to open a file write a structure to the file reopen the file and print the ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    115

    fread, fwrite

    Hello

    I am trying to open a file write a structure to the file
    reopen the file and print the structure on the screen.
    Something is wrong when i am writing the structe to the file
    Can anyone help?


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[])
    {
    
    	FILE *fptr;
    
    	struct test {
    		int getal;
    		char zin[11];
    	};
    
    	struct test tester;
    	struct test tester2;
    
    	tester.getal = 7;
    	scanf("%s", tester2.zin);
    
    	
    	if (argc != 2)
    		exit(0);
    
    	if ((fptr = fopen(argv[1], "wb")) == NULL)
    		exit(0);
    
    
    	fwrite(&tester, sizeof(tester), 1, fptr);
    
    	fclose(fptr);
    
    	if ((fptr = fopen(argv[1], "rb")) == NULL)
    		exit(0);
    
    
    	while(fread(&tester2, sizeof(tester2), 1, fptr) == 1)
    	{
    
    		printf("%i\n", tester2.getal);
    		printf("%s\n", tester2.zin);
    	}
    
    	return 0;
    }

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    This is a typo:
    Code:
    	tester.getal = 7;
    	scanf("%s", tester2.zin);
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    115
    yeah thats it

    Tyvm

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fread() & fwrite()
    By Roger in forum C Programming
    Replies: 2
    Last Post: 11-09-2009, 04:18 PM
  2. 2d array and fwrite and fread
    By totalnewbie in forum C Programming
    Replies: 14
    Last Post: 01-10-2009, 03:45 PM
  3. Weird problem with fwrite() and fread()
    By piote in forum C Programming
    Replies: 2
    Last Post: 11-13-2004, 03:07 PM
  4. buffer type for fread & fwrite
    By daluu in forum C Programming
    Replies: 5
    Last Post: 05-08-2003, 07:57 PM
  5. fread() and fwrite() ?
    By Limblet in forum C Programming
    Replies: 4
    Last Post: 09-25-2001, 08:36 PM

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