c - Can i use fgetc() or fputc() in a binary file? -
i creating archive program in c, , want save files provide, list , extract them.
had many issues because used text file saving, , not best choice if want process binary files music or photos, because when extract them, not executed correctly (they corrupted). in order solve problem, wanted create binary archive file.
code file writing (on extraction) following:
void scrivifile(const char * arrivo) //scrive file creati in precedenza { file * partenza; file * target; int c; int spazio = 'a'; int = 0; int pos; char * path; path = collegaslash(getcwd(null, 0), nome); partenza = fopen(path, "rb"); fseek(partenza, inizio, seek_set); target = fopen(arrivo, "wb"); //apro il file if (target) { //se รจ aperto while ((c = fgetc(partenza)) != eof && ftell(partenza)<=fine-10) { //e il carattere preso non eccede la fine del file fputc(c, target); fputc(c, stdout); pos = ftell(partenza); if(pos==fine) { break; } //scrivo lo stesso carattere in out (file in uscita) } // fclose(target); //chiudo il file fclose(partenza); } else { printf("errore di scrittura del file \n"); } } since need binary files extracted correctly, can use code wrote above, or have change fgetc() , fputc() functions fread() , fwrite()?
thanks
you're using fgetc() , fputc() can see man page descriptions these function:
fgetc() reads next character stream , returns unsigned char cast int, or eof on end of file or error.
fputc() writes character c, cast unsigned char, stream.
a character, in c, defined standard 1 byte (8 bits), means when use fxxxc() on file you'll 1 byte (that happens character in text file).
if extract , rebuild binary file, byte byte, you'll exact duplicate. no, there no issues using fgetc() , fputc() on binary file type. can prove simple example program... example:
int main() { file * fptr = fopen("small_pic.jpg", "rb"); // open existing binary picture char buffer[10000] = {0}; // pic 6kb or so, 10k bytes hold file * fptr2 = fopen("new_small_pic.jpg", "wb"); // open new binary file // our copy of pic unsigned long filelen; unsigned long counter; fseek(fptr, 0, seek_end); filelen=ftell(fptr); // exact size of pic fseek(fptr, 0, seek_set); for(counter=0; counter<filelen; counter++) fputc(fgetc(fptr),fptr2); // read each byte of small_pic.jpg , make // new pic fclose(fptr); fclose(fptr2); return 0; } end result: have 2 of exact same images, because fgetc() , fputc() can used on binary files.
Comments
Post a Comment