Linux Systemcall _file op

stat

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

int main(int argc,char* argv[])
{
    if(argc<2)
    {
        printf("./a.out filename\n");
        exit(1);
    }

    struct stat st;
    int ret=stat(argv[1],&st);

    if(ret==-1)
    {
        perror("stat");
        exit(1);
    }
    //get the size of a file
    int size=(int)st.st_size;
    printf("file size=%d\n",size);
}

lseek

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

int main()
{
    int fd=open("aa",O_RDWR);
    if(fd==-1)
    {
        perror("open file:");
        exit(1);
    }

    int ret=lseek(fd,0,SEEK_END);
    printf("file length = %d\n",ret);

    //file extention
    ret=lseek(fd,2000,SEEK_END);
    printf("return value: %d\n",ret);
    //write sth.
    write(fd,"a",1);




    close(fd);
    return 0;
}

read wirte

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

int main()
{
    int fd=open("english.txt",O_RDONLY);
    if(fd==-1)
    {
        perror("open file:");
        exit(1);
    }

    //create a new file
    int fd1=open("newfile",O_CREAT | O_WRONLY,0664);
    if(-1==fd1)
    {
        perror("open newfile:");
        exit(1);
    }

    //read file
    char buf[2048]={0};
    int count = read(fd,buf,sizeof(buf));
    if(-1 == count)
    {
        perror("read wrong:");
    }
    while(count)
    {
        //write the data read to another file
        int ret=write(fd1,buf,count);
        printf("wirte bytes %d\n",ret);
        //continue read file
        count=read(fd,buf,sizeof(buf));
    }

    //close files
    close(fd);
    close(fd1);

}

access

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc,char* argv[])
{
    if(argc<2)
    {
        printf("a.out filename\n");
        exit(1);
    }

    int ret=access(argv[1],W_OK);
    if(ret==-1)
    {
        perror("access");
        exit(1);
    }
    printf("you can wirte this file.\n");
    return 0;
}

unlink

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


int main()
{
    int fd=open("tmpfile",O_CREAT | O_RDWR,0664);
    if(fd==-1)
    {
        perror("open");
        exit(1);
    }
    //delete a file
    int ret=unlink("tmpfile");

    //wirte file
    write(fd,"Hello\n",5);

    //reset file pointer
    lseek(fd,0,SEEK_SET);

    //read file
    char buf[24]={0};
    int count=read(fd,buf,sizeof(buf));

    //print the content to screen
    write(1,buf,count);

    //close file
    close(fd);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/kaikai_sk/article/details/79925834
OP
今日推荐