Problem with file opening by C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ugurcan Sengit
    New Member
    • Apr 2011
    • 2

    Problem with file opening by C

    Hello , I'm new on programming and I'm trying to pass one more step to files. I wrote the following code and opened the " dosya.txt " file to true folder. At first I wrote it to G:\\dosya.txt , then I got null character as a return. After this I changed it to C:\\dosya.txt , now I got
    " Unhandled exception at 0x5521e42e (msvcr100d.dll) in asd.c.exe: 0xC0000005: Access violation writing location 0xcccccccc. " error and I don't know how to solve it. I think I didn't do anything wrong but my code doesn't work. Can you help me to solve this ? Thanks a lot :)

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    	int i,a[5];
    	FILE *ptr;
    	ptr = fopen("C:\\dosya.txt","r");
    	if(ptr==NULL)
    		printf("File does not exist !");
    	for(i=0;i<5;i++,ptr++)
    	{
    		fscanf(ptr,"%d",a[i]);
    		printf("%d\n",a[i]);
    	}
    }
  • Alex Bránya
    New Member
    • Apr 2011
    • 7

    #2
    Here is an answer:


    Code:
    //don't increase ptr manually, it's done by internal
    for(i=0;i<5;i++,ptr++)
    
    //this is the right format
    for(i=0;i<5;i++)

    Comment

    • Ugurcan Sengit
      New Member
      • Apr 2011
      • 2

      #3
      I just done what you've said but it still doesn't work. I got same error message :(

      Comment

      • Alex Bránya
        New Member
        • Apr 2011
        • 7

        #4
        I have compiled after modification, anyway try this:
        (I have compiled too, and it runs)


        Code:
        #include <stdio.h>
        #include <stdlib.h>
          int main()
          {
               int i;
               int a[]={19,21,9,3,75};  //initialize array
               FILE *ptr;
               ptr = fopen("C:\\dosya.txt","w");
               if(ptr==NULL)
               printf("File does not exist !");
               
        	   
               for(i=0;i<5;i++) 
               {		   
        	   fprintf(ptr,"%d",a[i]); //write to file
               }
        
        	rewind (ptr);  //reset file pointer
        
               for(i=0;i<5;i++) 
               {
                   fscanf(ptr,"%d",a[i]); //read from file
                   printf("%d\n",a[i]);   
               }
        
        		 fclose (ptr);
        
         }

        Comment

        Working...