文件编程

Linux 文件基础操作实例:open、close、read、write、lseek的用法
具体用法请在Linux终端输入man 2 + 指令名称 ,man手册上非常详细哦!
例如:man 2 open

以下三个常数中必须指定一个,且仅允许指定一个(这些常数定义在

#include
#include
#include
#include
#include
#include
#include
struct student                  //定义结构体
{
    char name[20];
    int id;
    float score;
};

typedef struct student Student;
int main()
{
    int fd, ret;

    Student student1 = {"fu sheng liu nian",20171206,100};  //结构体变量初始化
    Student tmp;

    fd = open("hello.txt", O_RDWR | O_CREAT , 0666);          //0666是定义文件属性
    printf("%d\n", fd);

    if (-1 == fd)   //文件打开失败,返回值为-1
    {
        perror("open");
        exit(1);
    }

    ret = write(fd, &student1, sizeof(Student));
    if (-1 == ret)    //文件写入失败
    {
        perror("write");
        exit(1);
    }

    ret = lseek(fd, 0, SEEK_SET);//0为偏移量
    if (-1 == ret)
    {
        perror("lseek");
        exit(1);
    }

    printf("%d\n", lseek(fd, 0, SEEK_END) - lseek(fd, 0, SEEK_SET));//计算文件长度

    ret = read(fd, &tmp, sizeof(Student));
    if (-1 == ret)
    {
        perror("read");
        exit(1);
    }
    printf("Read From Txt : %s\t%d\t%f\n",tmp.name, tmp.id, tmp.score );

    close(fd);  //文件打开后,记得要关闭文件哦!
    return 0;
}

你可能感兴趣的:(文件编程)