C language file operations related functions under linux

  • Read (open) file and write (write) another file
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>.h>
int main()
{
    int fd1=open("/home/cpc/Documents/diary",O_RDWR);
    printf("%d\n",fd1);
    int fd2=open("/home/cpc/Documents/anothernote",O_WRONLY|O_CREAT,0664);
    char buf[4096];
    int len=read(fd1,buf,sizeof(buf));
    while(len>0)
    {
        write(fd2,buf,len);
        len=read(fd1,buf,sizeof(buf));
    }
    return 0;
}
  • lseek dynamic expansion files
#include <stdio.h> 
#include <stdlib.h> 
#include < String .h> 
#include <fcntl.h> .h>
 int main () 
{ 
    int FD1 = Open ( " / Home / CPC / Documents / Diary " , O_RDWR | O_CREAT, 0664 );
     IF (fd1 == - 1 ) 
    { 
        perror ( " file the Read error " ); 
        Exit ( 1 ); 
    } 
    lseek (fd1, 1000 , SEEK_END); // make pointer to the end of the file raids , then 1000 bytes offset, the dynamic expansion is actually 
    return  0  ;
}

....... However ll view the file information by linux shell commands, file size has not changed

 

 ....... have to add a character as the original ending

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>.h>
int main()
{
    int fd1=open("/home/cpc/Documents/diary",O_RDWR|O_CREAT,0664);
    if(fd1==-1)
    {
        perror("file read error");
        exit(1);
    }
    lseek(fd1,1000,SEEK_END);
    write(fd1,"c",1);
    close(fd1);
    return 0;
}

Guess you like

Origin www.cnblogs.com/saintdingspage/p/12154527.html