- 论坛徽章:
- 0
|
我写了一个简单的复制文件的例子,
/* copy file */
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1024
int main(void)
{
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
FILE *source, *backup;
if ((source = fopen("source.dat", "rb")) == NULL)
{
printf("Error in opening file.\n");
exit(1);
}
if ((backup = fopen("backup.dat", "wb")) == NULL)
{
printf("Error in creating file.\n");
exit(1);
}
while (feof(source) == 0)
/* haven't reached the end of the file */
{
if (fread(buf, sizeof(char), sizeof(buf), source) < 1)
/* less than the length of buf, */
if (feof(source) != 0)
/* but haven't reached the end of file, which says a error happend */
{
printf("Error in reading file.\n");
break;
}
if (fwrite(buf, sizeof(char), sizeof(buf), backup) < 1)
/* the same like above */
{
if (feof(backup) != 0)
{
printf("Error in wrinting file.\n");
break;
}
}
}
if (fclose(source) == EOF)
{
printf("Error in close file.\n");
exit(1);
}
if (fclose(backup) == EOF)
{
printf("Error in close file.\n");
exit(1);
}
}
但相信里面有很多bug,有谁有完美的复制文件的例子?
顺便问一下,我想自己写一些linux下如cp ,rm , 等小工具,想做个借鉴,有没有类似源代码可以看? |
|