利用文件讀寫操作-完成大文件的複製粘貼

利用讀寫函數,完成對文件的複製,粘貼。

初級階段,文件的複製粘貼不使用多線程來搞(雖然之前開多線程來進行排序(此處手動狗頭))


說明:因爲文件往往很大,所以需要要到循環來讀文件,和寫文件。但是畢竟是模擬複製,粘貼。所以每次我就只讀10個字節的大小,然後寫到被粘貼文件中。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>


*先往:"copy.txt"裏面寫120字節的數據,其中的lseek求文件大小,在上一篇博客裏面已經說過了。*
int main()
{
    int fd = open("copy.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
    if(fd == -1)
    {
        perror("open error");
        exit(-1);
    }

    char * str = "hello world\n";
    int len = strlen(str);
    
    int i = 0;
    while(i < 10)
    {
        int ret = write(fd,str,len);
        if(ret == -1)
        {
            perror("write error");
            exit(-1);
        }
        i++;
    }

    off_t surrpos = 0;
    surrpos = lseek(fd,0,SEEK_END);
    printf("%d\n",surrpos);

	close(fd);
    return 0;
}

再來粘貼到文件"paste.txt"中,每次在"copy.txt"中讀10個字節到 "paste"中,直到讀到文件末尾。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

int main()
{
    int readfd = open("copy.txt",O_RDWR,0644);
    if(readfd == -1)
    {
        perror("open copy.txt error");
        exit(-1);
    }

    int writefd = open("paste.txt",O_RDWR|O_CREAT,0644);
    if(writefd == -1)
    {

        perror("open paste.txt error");
        exit(-1);
    }

    char buf[10];
    int ret = 0;
    while(ret = read(readfd,buf,sizeof(buf)))
    {
        if(ret == -1)
        {
            perror("read error");
            exit(-1);
         }

        ret = write(writefd,buf,ret);
        if(ret == -1)
        {
            perror("write error");
            exit(-1);
        }
    }

    off_t surrpos;
    surrpos = lseek(readfd,0,SEEK_END);
    printf("%d\n",surrpos);

	close(writefd);
	close(readfd);
    return 0;
}

總結:在實際應用中,一個進程讀文件的速度是遠遠不夠的。所以在後期會開多線程來讀寫文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章