1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C program: fopen()

  1. Aug 6, 2004 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Here's my assignment:

    Write code to open a file called adata.out, and write the contents of the following array out to it in binary form (with no data conversion).

    int a[5];


    My first question is, why I am I asked to write to a file with the extension .out? Why not .txt?

    My second question is, is fopen() what I should use to open a file for writing to it?

    Thanks for your help!!
     
  2. jcsd
  3. Aug 6, 2004 #2
    There is no particular reason. The only difference is that Windows will not automatically know to open the file using Notepad (or whatever program you have associated with .txt files.) The extension is mostly cosmetic.

    Sure - or reading from it, or appending to it, or reducing its length to zero, or...

    fopen is pretty versatile, the difference between reading and writing is controlled by one of the parameters, which is a string whose value is "r" for read, or "w" for write, or "a" for append, and so on. Look up the function definition in your reference of choice to see all the possible values.

    fopen isn't the only thing you could use to do this. File streams are another alternative, and there are other alternatives as well.
     
  4. Aug 6, 2004 #3

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, Zorodius. I think part of the reason I was getting so confused about fopen() is I wasn't supplying the right number of arguments. Can I just give it a filename as an argument like this?
    fopen(atextfile.txt , "r")
    to read a file.
    The example I have been studying at takes a command line argument for the file name but I am thinking that for this exercise he wants me to have the name of the file specified in the program rather than having the user put it in at the command prompt.
    thx.
     
  5. Aug 6, 2004 #4
    fopen() returns a pointer to a file if fopen successfully opens the chosen file. You need to do somethin like this:

    PHP:

    #include <stdio.h>

    int main() {
      FILE *pfile; /* File pointer to desired file */

      pfile = fopen("{full path to file}/adata.out", "ab");  /* opens file append-binary replace {path} with actual path unless file and exe are in same directory */


      /* the following chunk is used to to see if the file opened is empty or not */
      if(pfile==NULL)
        {
          printf("Error: can't open file.\n");
          return 1;
        }
    }
     
    I believe the above is correct.

    Good luck.
     
  6. Aug 6, 2004 #5

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks very much, Faust. I think seeing the example helps a lot - I can play around it with it and try some different things. :smile:
     
  7. Aug 7, 2004 #6
    Just for emphasis: No, you would never specify the file name like that, because you haven't told the compiler that it's a string. If you write fopen(atextfile.txt, "r") the compiler thinks atextfile.txt is part of your code. You'll get a syntax error. Instead, if you write fopen("atextfile.txt", "r") then the double quotes around atextfile.txt tell the compiler that it is a string.
     
  8. Aug 7, 2004 #7

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Hello all,
    OK, I have something sorta working now (I am getting the file open and a change is occuring), but I am still having problems.

    I have a file called adata.out on my C: drive. It contains the text hello.
    Next I run this:

    PHP:
     
    #include <stdio.h>
    int main() {
        int a[5] = {1,2,3,4,5};
        FILE *pfile; /* File pointer to desired file */
        int i = 0;

      pfile = fopen("adata.out", "ab");  /* opens file append-binary */
      /* the following chunk is used to to see if the file opened is empty or not */
      if(pfile==NULL)
        {
          printf("Error: can't open file.\n");
          return 1;
        }
      else
        for(i =0;i<5;i++)
          putc(a[i], pfile);
        return 0;
    }
     
     
    and when I open the file back up the text now reads
    hello

    I am not sure if this is what it's supposed to do. He specifies to write the contents of the array in binary form with no data conversion. Also, what does using return 1; accomplish when the check is done to open the file? I read in my book that returning 0 is the same as using the statement exit(0); but I am not sure what 1 does. Thanks! :smile:
     
  9. Aug 7, 2004 #8
    That's what it's supposed to do (when you open the file (presumably with a text editor of some sort) it tries to associate the numbers 1, 2, ..., 5 you appended to the file with their ASCII codes. These ASCII codes happen to stand for control characters (e.g 2 = "start of text") but they're kind of misplaced the middle of the file like that, so they show up as squares (i.e the editor doesn't really know what to do with them)). Changing int a[5] = {1,2,3,4,5}; to int a[5] = {'1','2','3','4','5'}; will probably yield the result you expected...

    And as you probably know, "return;"-ing from the main() function will terminate the program. The number after return is known as the exit code (I think), and is (AFAIK) very rarely used on Windows. You could, in theory, "intercept" the exit code and display it. This could be used for debugging purposes (if the exit code is 1, the program failed to open the file, if it is 0, everything went alright. Of course, you already have printf()s in place which gives the same information but in a less cryptic fashion ;)).
     
    Last edited: Aug 7, 2004
  10. Aug 7, 2004 #9

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, Muzza. I think I might just eliminate the return 1; from the if statement, since I am not using it to test anything.

    Actually I ended up cutting out the if statement altogether. I am now using write-binary string mode to open and write to the file since I don't think I need to append to anything. Plus, it creates adata.out for me if the file isn't found, so that's kinda handy.
     
    Last edited: Aug 7, 2004
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C program: fopen()
  1. C program issues (Replies: 2)

  2. C++ Program Ideas (Replies: 9)

Loading...