50 การ copy ไฟล์


  • การ copy ไฟล์ไม่มีไลบรารี่ให้ใช้ แต่ทำได้โดยการเปิดในโหมด binary และเขียนไว้ที่ไฟล์ใหม่
  • ใช้ feof ในการเช็ก EOF
  • ความแตกต่างระว่าง text mode กับ binary mode คือ text mode จะทำการแปลความหมายของ ตัวขึ้นบรรทัดใหม่ (‘\n’) . ส่วน binary mode จะไม่ทำการแปลความหมายของข้อมูลใดๆทั้งสิ้น
  • EOF อยู่ใน stdio.h มีค่าเท่ากับ -1

#include <stdio.h>
#include <string.h>
int copyFile(char *oldName , char *newName);
int main(void)
{
char newName[] = "CopyZenXX.jpg";
int i,j,counter = 1;
for(i = 0 ;i < 9;i++)
{
for(j = 0;j<9;j++)
{
newName[7] = i + '0';
newName[8] = j + '0';
if(copyFile("zen.jpg",newName)==0)
{
printf("Copy successful %d\n",counter++);
}
}
}
return 0;
}
int copyFile(char *oldName , char *newName)
{
FILE *source , *dest;
source = fopen(oldName,"rb");
if(source == NULL) return (-1);
dest = fopen(newName,"wb");
if(dest == NULL)
{
fclose(source);
return (-1);
}
int c;
while(1)
{
c = fgetc(source);
if(feof(source)) break;
fputc(c,dest);
}
fclose(source);
fclose(dest);
return 0;
}
view raw B50_Copy_file.c hosted with ❤ by GitHub