Linux中C语言文件操作

来源:互联网 发布:java现在的就业前景 编辑:程序博客网 时间:2024/05/22 07:49

在linux下,一切皆文件。

通常在进程启动时候,都会打开三个文件—–标准输入、标准输出和标准出错处理。
这三个文件所对应的文件描述符分别是0,1和2。
对应的宏是:
STDID_FILENO==0
STDOUT_FILENO==1
STDERR_FILENO==2
所以用户在打开新的文件时候,返回的文件描述符一般是从3开始的。

不带缓存的IO操作主要使用下面6个函数:
create:创建新文件
open:打开文件
read:读取已经打开的文件内容
write:向已经打开的文件写入内容
lseek:用于移动文件的读写位置
close:关闭已经打开的文件

这六个函数所需要的头文件是:

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

创建Demo:

#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>void create_file(char *filename){    int fd;    fd = creat(filename,0755);    if(fd < 0)    {        // printf("fd = %d \n", fd);        printf("create file failure \n", fd);        exit(EXIT_FAILURE);    }    else    {        printf("create file success!\n");    }}int main(int argc, char *argv[]){    int i;    if(argc < 2)    {        printf("you don't input file name!\n");        exit(EXIT_FAILURE);    }    for(i=1; i < argc; i++)    {        create_file(argv[i]);    }    exit(EXIT_SUCCESS);}

测试代码:

gcc -o create_file create_file.c./create_file ../tete.txt  //表示在父目录新建文件

打开Demo:

#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>int main(int argc, char * argv[]){    int fd;    if(argc < 2)    {        puts("No input file name! \n");        exit(1);    }    fd = open(argv[1], O_CREAT|O_RDWR, 0755);    if(fd < 0)    {        perror("open file failure! \n");        exit(1);    }    else    {        printf("open file %d success! \n", fd);    }    close(fd);    exit(0);}

把一个文件的内容复制到另一个文件中区(Demo):

#include<sys/stat.h>#include<fcntl.h>#include<errno.h>#include<stdio.h>#include <string.h>#define BUFFER_SIZE 1024int main(int argc, char *argv[]){    int from_fd,to_fd;    long file_size = 0;    int ret = 1;    char buffer[BUFFER_SIZE];    char *ptr;    if(argc != 3)    {        fprintf(stderr,"Usage: %s fromfile tofile \n", argv[0]);    return -1;    }    from_fd = open(argv[1],O_RDONLY);    if(from_fd < 0)    {    fprintf(stderr,"Open %s \n", argv[1]);        return -1;    }    to_fd = open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);     if(to_fd < 0)    {    fprintf(stderr,"Open %s \n", argv[2]);        return -1;    }       file_size = lseek(from_fd,0L,SEEK_END);    lseek(from_fd,0L,SEEK_SET);//    printf("form file size is %ld\n",file_size);    while(ret)    {    ret= read(from_fd, buffer, BUFFER_SIZE);    if(ret == -1)    {        printf("Read Error! \n");        return -1;    }    write(to_fd, buffer, ret);    file_size -= ret;     //bzero() 会将内存块(字符串)的前n个字节清零    //s为内存(字符串)指针,n 为需要清零的字节数    bzero(buffer,BUFFER_SIZE);    }    close(from_fd);    close(to_fd);    return 0;}

仅当做笔记。

1 0
原创粉丝点击