C Programming: Using fopen() to Write Files

  • Thread starter Thread starter Math Is Hard
  • Start date Start date
  • Tags Tags
    Program
Click For Summary

Homework Help Overview

The discussion revolves around a programming assignment involving the use of the fopen() function in C to write an array to a binary file named adata.out. Participants explore the rationale behind file extensions and the appropriate usage of fopen() for file operations.

Discussion Character

  • Exploratory, Conceptual clarification, Problem interpretation

Approaches and Questions Raised

  • Participants question the choice of file extension (.out vs .txt) and discuss the implications of using fopen() for file writing. There are inquiries about the correct syntax for specifying file names and the handling of file pointers. Some participants share code snippets and their experiences with file operations.

Discussion Status

The discussion is active, with participants providing insights and clarifications on the use of fopen(). Some have shared code examples that illustrate their understanding, while others express confusion about specific aspects of file handling and error checking. There is no explicit consensus, but various interpretations and approaches are being explored.

Contextual Notes

Participants mention issues related to the expected output format when writing binary data and the significance of return values in the context of error handling. There are also references to the behavior of file operations when the specified file does not exist.

Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
Messages
4,663
Reaction score
36
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:

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 33 ·
2
Replies
33
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
7
Views
3K
  • · Replies 20 ·
Replies
20
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 22 ·
Replies
22
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 32 ·
2
Replies
32
Views
4K
  • · Replies 4 ·
Replies
4
Views
1K