fwrite problem, cannot write in binary file! [duplicate]
Possible Duplicate:
C Programming - File - fwrite
include.... >
int main(void)
{
FILE *Archivo;
int proba=5;
Archivo=fopen("md3.dat", "ab+");
fwrite(&proba, sizeof(int), 1, Archivo);
fclose(Archivo);
printf("Bye!\n\n");
}
I just can't print any number on the binary fila md3.dat, please help!
I think OP is expecting fwrite
to behave as fprintf
and write an ASCII decimal string the the file, then getting confused when the output is the bytes 5,0,0,0
(all non-printable characters) which probably shows up blank when opening it in an editor or using cat
to print it to the terminal (or type
on DOS).
If you want to write text, use fprintf
.
Try this:
Archivo = fopen("md3.sat", "wb+");
fseek(Archivo, 0, SEEK_END);
fwrite(&proba, sizeof(int), 1, Archivo);
This should write your int
value at the end of the file. Also, you should check for function return values. Remember: you are in C!!.
int written;
Archivo = fopen("md3.sat", "wb+");
if (Archivo != NULL) {
fseek(Archivo, 0, SEEK_END);
written = fwrite(&proba, sizeof(int), 1, Archivo);
printf("%d int values written!\n", written);
}
精彩评论