And*_*rdi 4 c fwrite fread fgetc
我正在用C创建一个归档程序,我想要它保存我提供的文件,列出并提取它们.
我有很多问题,因为我使用文本文件进行保存,如果我想处理音乐或照片等二进制文件,它不是最佳选择,因为当我提取它们时,它们没有正确执行(它们已损坏).为了解决这个问题,我想创建一个二进制存档文件.
文件写入代码(提取时)如下:
void scriviFile(const char * arrivo) //scrive i file creati in precedenza
{
FILE * partenza;
FILE * target;
int c;
int spazio = 'a';
int i = 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");
}
}
Run Code Online (Sandbox Code Playgroud)
由于我需要正确提取二进制文件,我可以使用上面编写的代码,还是我必须用和更改所有fgetc()
和fputc()
函数?fread()
fwrite()
谢谢
您正在使用fgetc()
并且fputc()
从手册页描述中可以看到这些功能:
fgetc()从流中读取下一个字符并将其作为unsigned char转换为int,或者在文件末尾或错误时返回EOF.
fputc()将字符c(强制转换为无符号字符)写入流.
C中的字符由标准定义为始终精确为1字节(8位),这意味着当您fxxxc()
在文件上使用时,您将获得1个字节(恰好是文本文件中的字符).
如果逐字节提取并重建二进制文件,则会得到完全相同的重复.所以不,使用fgetc()
和fputc()
二进制文件类型没有问题.你总是可以通过一个简单的示例程序向自己证明这一点......例如:
int main()
{
FILE * fptr = fopen("small_pic.jpg", "rb"); // open existing binary picture
char buffer[10000] = {0}; // the pic is 6kb or so, so 10k bytes will hold it
FILE * fptr2 = fopen("new_small_pic.jpg", "wb"); // open a new binary file
// for our copy of the pic
unsigned long fileLen;
unsigned long counter;
fseek(fptr, 0, SEEK_END);
fileLen=ftell(fptr); // get the exact size of the pic
fseek(fptr, 0, SEEK_SET);
for(counter=0; counter<fileLen; counter++)
fputc(fgetc(fptr),fptr2); // read each byte of the small_pic.jpg and make
// a new pic from it
fclose(fptr);
fclose(fptr2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
最终结果:我们有两个完全相同的图像,因为fgetc()
并且fputc()
可以用于二进制文件.