开发者

fwrite problem, cannot write in binary file! [duplicate]

开发者 https://www.devze.com 2023-01-28 10:03 出处:网络
This question already has answers here: 开发者_JS百科 Closed 12 years ago. Possible Duplicate: C Programming - File - fwrite
This question already has answers here: 开发者_JS百科 Closed 12 years ago.

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消