opening files and use of fseek to get size of file - C++

853 Views Asked by At

I am doing one program with c++ and this program should be a lexical analyser to make a compiler. Thus I have made the header "AnalisadorLexical.h" where I defines all the functions and all the other things as pointers to files..., the "AnalisadorLexical.cpp" where I defines the logical of the functions and the main.cpp.

At the main.cpp I ask to the user to enter the name of the file to analyse and the name of to write the result. This is done inside a loop while for that the user enter many files to analyse. When the user enter the name of font file and the name o the final file I use the function fopen twice to open the first file and to write on the second. After this I invoke the constructor to get the size of the first file to create a vector where I will store the tokens of the file. My problema is when I use the fseek to get the size of the file. The execution of the program failure and I don't know what to do.

Follows their code.

main.cpp:

`int main(){

char *c1, *c2; 
c1 = new char[30]; 
c2 = new char[30]; 

FILE *f1; 
FILE *f2; 

cout<<"Arquivo de entrada:"<<endl; 

while(cin>>c1){

    cin>>c2; 

    f1 = fopen(c1, "r"); 
    f2 = fopen(c2, "w"); 

    AnalisadorLexico al(f1, f2);
    al.analiseLexica(); 
    fclose(f1); 
    fclose(f2); 
} 

return 0; }`

AnalisadorLexico.cpp - the constructor:

` AnalisadorLexico::AnalisadorLexico(FILE* f1, FILE* f2){

//Aloca os arquivos 
fp = f1;//arquivo sendo lido (de entrada)
fs = f2;//arquivo de saída

//tamanho do arquivo 
fseek(fp, 0L, SEEK_END);

tk_Size = ftell(fp);

//vetor de tokens 
tk_vet = new token[tk_Size];

//inicializa com 0
tk_count = 0;

monta_tabelaPR();
montaSb_vet();

}(...) `

AnalisadorLexico.h - the definition of constructor

` (...)

public:

//Construtor de classe 

AnalisadorLexico(FILE *f1, FILE *f2);

(...) `

Thank for your help guys.

2

There are 2 best solutions below

2
David Schwartz On

You need to check the return value of fopen. If there's an error, you need to do something sane about it. Also, why aren't c1 and c2 std::strings?

0
Dietmar Kühl On

I wouldn't bother trying to find the size of the file. However, I also wouldn't stick it into manually allocated memory. Instead, I would just read it into a std::vector<char> and get on with the work I'd actually have to do:

std::vector<char> v;
{
    std::ifstream in(c1);
    if (!in) {
        throw std::runtime_error("failed to open '" + std::string(c1) "' for reading");
    }
    v.insert(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}