Linux环境编程:打开open函数创建的文件,然后对此文件进行读写操作。。。

打开open函数创建的文件,然后对此文件进行读写操作(将文件打开属性改为可读可写,文件权限要做相应更改)。接着,写入“Hello!I am writing to this file!”,此时文件指针位于文件尾部。接着再使用lseek函数将文件指针移动文件开始处,并读出10个字节并将其打印出来
2026年09月26日 17:15
有1个网友回答
网友(1):

#include 
#include 
#include 
#include 
#include 
#include 

int main() { 
    int fd = -1; 
    fd = open("zhidao_561804018.dat", O_CREAT | O_TRUNC | O_RDWR, 0666);
    if (fd < 0) {
        perror("open");
        return -1; 
    }   
    char buff[64];
    strcpy(buff, "Hello!I am writing to this file!");
    int count = strlen(buff);
    if (write(fd, buff, count) < 0) {
        perror("write");
        return -1; 
    }   
    if (lseek(fd, 0, SEEK_SET) < 0) {
        perror("lseek");
        return -1; 
    }   
    if (read(fd, buff, 10) < 0) {
        perror("read");
        return -1; 
    }   
    buff[10] = 0x00;
    printf("%s\n", buff);
    if (fd > 0) {
        close(fd);
        fd = -1; 
    }   
    return 0;
}