!(f=fopen()) ?

Why do we need to use 'f=' when opening a file in this if statement?
I should preface I have a variable on top called

 
FILE *f=stdin;


1
2
3
4
5
6
else if( !(f=fopen(fileName=*argv,"r") ) )
{
    printf("Condition: program.exe <your-file.txt>\n");
    return 1;
}
		
If the fopen() succeeds (return value is not null) then presumably you then want to perform some operation on the file. For this you need to have a correctly set variable f to the file stream. Hence f = fopen() in L1 above.
Understood so you are saying if we want to do f.close() in the future? otherwise it will run amok
note that this is C, not c++, which you may already know but once in a while someone uses C code inside C++ (valid to do) unknowingly.

all file operations including close should be done ONLY on a VALID file variable (open succeeded). You should close any file you successfully opened. Modern OS may do this for you when a program ends, but you must not assume this will happen.
The problem you are facing is C’s dense syntax.

Let us rewrite the problem in a more straight-forward way — which incidentally allows us to correct some errors!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  const char * filename = argv[1]; // index of FIRST program argument
  if (!filename)
  {
    fprintf( stderr, "usage:\n  program.exe <your-file.txt>\n" );
    return 1;
  }

  FILE * f = fopen( filename, "r" );
  if (!f)
  {
    fprintf( stderr, "error: unable to open file \"%s\"\n", filename );
    return 1;
  }

  ...

  fclose( f );

The general pattern is:
  • declare and assign value to variable
  • validate value (for example, filename must not be NULL)

As already mentioned, using fopen() and fclose() is C. C++ makes file handling infinitely easier and less error-prone.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  if (argc != 2)
  {
    std::cerr << "usage:\n  program.exe <your-file.txt>\n";
    return 1;
  }

  std::string filename = argv[1];
  std::ifstream f( filename );
  if (!f)
  {
    std::cerr << "error: unable to open file \"" << filename << "\"\n";
    return 1;
  }

  ...

  std::string s;
  getline( f, s );  // read a line of text from `f`

  ...

  // no need to worry about closing `f` — it is automatically managed 

The ability to avoid jumping through the hoops C requires to safely read a line of text is reason enough to want to use C++.

Hope this helps.
dialer wrote:
so you are saying if we want to do f.close() in the future?

If you want to do anything with the file.
Read, write, close -- for all those you do need a handle to the file object, the f.

If you have no intention to do anything with the file, then why did you open it?
Topic archived. No new replies allowed.