Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File returns garbage, but writes correctly

Tags:

c

file

fopen

fwrite

I'm writing a struct into a file, but it returns garbage. Here is my code:

ptFile = fopen("funcionarios.dat", "ab+");
fwrite(&novoFunc, sizeof(strFunc), 1, ptFile);

The values of struct novoFunc, before and after the fwrite are not garbage. However, when I return the file values:

ptFile = fopen("funcionarios.dat", "rb+");
[...]

fseek(ptFile, i*sizeof(strFunc), SEEK_SET); //on the loop, i goes from 0 to total structs
fread(&funcionario, sizeof(strFunc), 1, ptFile);

printf("Code: %d; Name: %s; Address: %s; CPF: %d; Sales: %d\n", funcionario.codigo, funcionario.nome, funcionario.endereco, funcionario.cpf, funcionario.numVendas);

Any idea why? The code was working fine, and I dont remember doing significative changes.

Thanks in advance

Edit: Struct definition

typedef struct func{

    int codigo;
    char nome[50];
    char endereco[100];
    int cpf;
    int numVendas;
    int ativo;


} strFunc;

Edit2: It just got weirder: it works fine on linux (using netbeans and gcc compiler), but it doesnt on windows (devcpp and codeblocks). Well, the entire code is here:

http://pastebin.com/XjDzAQCx

the function cadastraFucionario() register the user, and when I use listaFuncionarios(), to list all the registered data, it returns the garbage. Here is a print of what listaFuncionarios() returns:

http://img715.imageshack.us/img715/3002/asodfadhf.jpg

Im sorry the code isnt in english

like image 516
Renato Siqueira Massaro Avatar asked Dec 29 '25 00:12

Renato Siqueira Massaro


1 Answers

You say: "The code was working fine, and I dont remember doing significative changes."

When it was working fine, it wrote some structures into your file.

Maybe later it was still working fine, and it appended some additional structures at the end of your file. The original data still remained at the beginning of your file. So when you read the beginning of the file, you read the original data. Maybe.

Are you sure that you read garbage? Are you sure that you didn't just read old data?

In your code:

ptFile = fopen("funcionarios.dat", "ab+");

Appending is the right thing to do for some purposes but not for others. Do you need wb+ instead?

like image 167
Windows programmer Avatar answered Dec 31 '25 15:12

Windows programmer