Thread: read write to file problem

  1. #1
    That weird Java guy xniinja's Avatar
    Join Date
    Jun 2010
    Posts
    231

    Question read write to file problem

    this might be a stupid mistake but here it goes
    I made a simple program that is supposed to write "1234" to a .txt file then it reads it back to you (why would this be useful, it's not, it is just a test). Ok so it writes to the file but it doesn't read from the file it just reads:
    2293520
    please help.
    here is the code
    Code:
    #include <stdio.h>
    
    int main()
    {
    	int num1[10];
        FILE *fp;
         fp = fopen("database.txt","w");
         if (fp == NULL)
         {nullfile();}
         fprintf(fp,"1234");
         fp = fopen("database.txt","r");
         if (fp == NULL)
         {nullfile();}
         fscanf(fp,"%d",num1);
         printf("%d",num1);
         getch();
    }
    
    int nullfile()
    {
       printf("file cannot be found");
               getch();
            return 0;
        }

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    fp is already open, you don't close it before opening it again (you don't close it all btw). But, it's not necessary to do since you can open the file in both read and write mode by using "w+", or "a+" if you want to add to a file that already exists (look up a man page for fopen). But then you need to rewind the file pointer before reading.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Replies: 2
    Last Post: 09-13-2006, 01:14 PM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  5. Can I write & read file in same program?
    By chad03 in forum C Programming
    Replies: 2
    Last Post: 08-04-2003, 08:39 AM