Note that there are some explanatory texts on larger screens.

plurals
  1. POOpening a file from within a function
    primarykey
    data
    text
    <p>I'm working on a piece of homework and I want to send a FILE * into a function as an argument since I have to open 3 files in an identical manner with some "flavor text". I got it to work fine like this: </p> <pre><code>enum {IN, STAT, REPRINT} FNAMES; #define FNAME_MAX 256 int main(void) { FILE *in, *stat, *reprint; char fnames[3][FNAME_MAX]; // store actual file names input by user char format[11]; // format identifier used in scanf for file names in = stat = reprint = NULL; // TODO: Check necessity buildFormat(format); // this translates FNAME_MAX into the string "%256s[^\n]" // TODO: Find out why this cannot be put into a function! // open the input file while (in == NULL) { // get input file name getFileName(format, fnames[IN]); // simply prompts for a file name/path // open the input file for reading in = fopen(fnames[IN], "r"); // make sure it opened if (in == NULL) printf("%s did not open, please check spelling/path.\n\n", fnames[IN]); else printf("%s was opened successfully.\n\n", fnames[IN]); } return 0; } </code></pre> <p>What will not work is this:</p> <pre><code>void openFile(FILE *in, char *format, char *fname, char *openFor) { // TODO: Find out why this cannot be put into a function! // open the input file while (in == NULL) { // get input file name getFileName(format, fname); // simply prompts for a file name/path // open the input file for reading in = fopen(fname, openFor); // make sure it opened if (in == NULL) printf("%s did not open, please check spelling/path.\n\n", fname); else printf("%s was opened successfully.\n\n", fname); } } </code></pre> <p>if I put file reading operations in the function it works fine, but if I go back to main and try to use the file pointer I sent in it doesn't work.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload