C Programming - File - fwrite

纵然是瞬间 提交于 2019-12-02 11:51:05

Try adding fflush(Archivo); to force a write of all buffered data.

Also, this statement: if(current->Id_Doctor=='\0') really ought to be an else since there is no other thing it can be but '\0'

Three things:

  • Make sure your fopen is successful.

    Archivo=fopen("md.dat", "ab+");
    if (Archivo == NULL)
    {
         perror("Failed to open file Archivo");
         ...
    }
    
  • Make sure you are checking the success of your fwrite's.

    if (fwrite(&id_doc, sizeof(id_doc), 1, Archivo) < 1)    
    {    
         perror("Failed to write to file Archivo");
         ... 
    }
    
  • Make sure you have a fclose to close the file properly.

    if (fclose(Archivo) != 0)    
    {    
        perror("Failed to close file Archivo");     
        ...
    }
    

Now that you've post a full sample of your code I guess I should ask if error checking is just left out for brevity? If not, you should think about adding it.

If you're expecting the value of id_doc to be in display format in the output file you'll have to convert the int to a string (using snprintf or similar) and write the string to the output file instead.

fwrite(&id_doc, sizeof(char), 1, Archivo); 

If you defined id_doc as anything other than a char it will write \0 to the file.

Much cleaner would be:

fwrite(&id_doc, sizeof(id_doc), 1, Archivo); 

If your first current is an Id_Doctor you have an endless loop.

If there is no current after your last current that is not an Id_Doctor, you get an illegal pointer derefenciation.

For your Problem: try the flush() family.

You're passing a pointer to a FOUR-BYTE INT, but only writing ONE BYTE (the wrong byte)!

Solution: declare id_doc as "char", not "int".

You have previously written the strings "\n<md>\n" and"<id_doctor> " to the file Archivo, which seems to indicate that it is not a binary file at all, but rather an XML-style file.

In this case, what you almost certainly want is:

fprintf(Archivo, "%d", id_doc);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!