Ready to work:
- Source file: file_sourse
- Destination file: file_goal
- Execution file: file_ex.c (the files that need to be compiled and executed use gcc commands)
Main code
FILE *fp,*fp1;
int cnt;
char buf[1024];
fp=fopen("file_sourse","r");
fp1=fopen("file_goal","w");
fcloseall();
while((cnt=fread(buf,1,sizeof(buf),fp)>0))
{
fwrite(buf,1,cnt,fp1);
}
If you want to copy it again, you need to use it herefseek function
fseek(fp,0,SEEK_SET);//重新定位到文件起始处
while((cnt=fread(buf,1,sizeof(buf),fp)>0))
{
fwrite(buf,1,cnt,fp1);
}
fcloseall();
r Open the file in read mode, throw an exception if the file does not exist
r+ Open the file in read and write mode, and throw an exception when the file does not exist
rs+ Open the file in synchronous read and write mode, notify the operating system to ignore the system cache (not recommended Use)
w to open the file in the form of writing, if the file does not exist, create it, and overwrite it if it exists.
wx Similar to w, except that the operation will fail when the file exists.
w+ Open the file in the form of reading and writing, and create it if the file does not exist. , If it exists, overwrite
a. Open the file in append form. If the file does not exist, create
ax. Similar to a, if the file exists, the operation will fail.
a+ Open the file in the form of read and write. If the file does not exist, create
ax+. Similar to a+, The operation will fail if the file exists
Main code
int fd,fd1;
int cnt;
char buf[1024];
fd=open("file_sourse",O_RDONLY);
fd1=open("file_goal",O_WRONLY | O_CREAT,0644);
close(fd);
close(fd1);
while((cnt=read(fd,buf,sizeof(buf))>0))
{
write(fd,buf,cnt);
}
If you want to copy it again, you need to use it herelseek function
lseek(fd,0,SEEK_SET);//重新定位到文件起始处
while((cnt=read(fd,buf,sizeof(buf))>0))
{
write(fd,buf,cnt);
}
close(fd);
close(fd1);
Combining the above two different methods for file copying function, it is not difficult to draw the similarities between the two methods. There is no need to rote memorize how to use these methods. Through daily practice, we will have an impression in our minds. , Plus the use of Linux systemmanCome to help, you will become more and more proficient in understanding and even knowing how to use it.
If there are any shortcomings, please point out, thank you! ! !