C Programming: Using fopen() to Write Files

  • Thread starter Thread starter Math Is Hard
  • Start date Start date
  • Tags Tags
    Program
AI Thread Summary
The discussion revolves around using the `fopen()` function in C to write an integer array to a binary file named `adata.out`. Participants clarify that the `.out` extension is cosmetic and does not affect file functionality, while `fopen()` is indeed the correct function for opening files for writing. A user demonstrates how to open the file in binary append mode and checks for errors in file opening. The conversation also addresses the confusion around using strings in `fopen()` and the implications of return codes in C programs. Ultimately, the user decides to switch to write-binary string mode for simplicity, allowing for file creation if it doesn't exist.
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
Messages
4,650
Reaction score
39
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!
 
Physics news on Phys.org
Math Is Hard said:
My first question is, why I am I asked to write to a file with the extension .out? Why not .txt?
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.

Math Is Hard said:
My second question is, is fopen() what I should use to open a file for writing to it?
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.
 
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.
 
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.
 
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:
 
Math Is Hard said:
Can I just give it a filename as an argument like this?
fopen(atextfile.txt , "r")
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.
 
Hello all,
OK, I have something sort of working now (I am getting the file open and a change is occurring), 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:
 
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:
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:
Back
Top