网站开发技术

记点笔记、 学点技术 欢迎交流建站技术。本站关注lamp技术

您尚未登录。

#1 2015-01-27 16:44:23

admin
管理员

linux c语言, 文件的读写, 对文件内部指针示例

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

int main () {
    char *s = "123456789";
    int fd;
    off_t currpos;
    char c;

    fd = creat("new.txt", 0644);
    if(fd == - 1) {
        perror("error");
        _exit(1);
    }
    // 写如数据
    if(write(fd, s, strlen(s)) == -1) {
        perror("write fail");
        _exit(2);
    }
    close(fd);



    fd = open("new.txt", O_RDWR | O_APPEND);
    if(fd == -1) {
        perror("error");
        _exit(1);
    } else {
        currpos = lseek(fd, 0, SEEK_SET);
        printf("this offset if is %d \n", currpos);
        currpos = lseek(fd, 0, SEEK_END);
        printf("this offset if is %d \n", currpos);
    }
    close(fd);


    // 文件的读取


    fd = open("new.txt", O_RDONLY);

    while(1) {
        // 使用一个静态变量,防止无限循环
        static int count = 0;
        // 这里一次只读一个字符
        if(read(fd, &c, 1) != 0) {
            putchar(c);

        } else {
            break;
        }
        // lseek(fd, 0, SEEK_SET);  // 如果有这一行只能打印第一个字符,因为移动文件的指针
        // lseek(fd, 0, SEEK_CUR);  // 这一行没有什么用
        // lseek (fd , 0, SEEK_END);// 如果有了这一行, 仅仅输出一个1, 就结束了。 文件的内部的指针移动到最后了。

        count++;

        if(count > 100) break;
    }
    close(fd);

    return 0;
}



ipbbs.net

离线

页脚

Powered by FluxBB