Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why FILE pointer need to be declared out main() in Visual Studio 2010?

Tags:

c

visual-c++

c89

I was trying to compile a simple ansi C example in Visual Studio 2010 and came across with this error compiling:

Error: patchC.c(5): error C2275: 'FILE' : illegal use of this type as an expression

Program1:

#include <stdio.h>

int main(void) {
    printf("Hello world!\n");
    FILE *fp;
    fp = fopen("test.txt", "r");
    return 0;
}

The same program compiles without errors in gcc v4.5.2.

But, if I put the "FILE *fp;" line out of the main(), the program compile gracefully.

Program2:

#include <stdio.h>

FILE *fp;

int main(void) {
    printf("Hello world!\n");
    fp = fopen("test.txt", "r");
    return 0;
}

I don't figure out why this behavior, anyone could answer?

like image 720
Juliao Avatar asked May 04 '11 02:05

Juliao


People also ask

What is the correct way of declaring file pointer variable?

Declaring a File Pointer A file is declared as follows: FILE *fp; //fp is the name of the file pointer.

Why do we need file pointer?

A file pointer stores the current position of a read or write within a file. All operations within the file are made with reference to the pointer. The data type of this pointer is defined in stdio. h and is named FILE.

Why do we use pointers for files in C?

For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. For Example: FILE *fp; To open a file you need to use the fopen function, which returns a FILE pointer.


1 Answers

The Visual C++ compiler only supports C90. In C90, all local variable declarations must be at the beginning of a block, before any statements. So, the declaration of fp in main needs to come before the printf:

int main(void) {
    // Declarations first:
    FILE *fp;

    // Then statements:
    printf("Hello world!\n");
    fp = fopen("test.txt", "r");
    return 0;
}

C99 and C++ both allow declarations to be intermixed with other statements in a block. The Visual C++ compiler does not support C99. If you compiled your original code as a C++ file (with a .cpp extension), it would compile successfully.

like image 163
James McNellis Avatar answered Sep 20 '22 05:09

James McNellis