栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

UNIX-文件IO函数使用范例

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

UNIX-文件IO函数使用范例


#include 
#include 
#include 
#include 
#include 

void open_readMode(const char*);
void open_writeMode(const char*);
void open_lseek(const char *pathname);
void standard_io(const char *ptr_input);

int main()
{
    const char *pathname = "./file.rtf";
    const char *pathname2 = "./file2";
    //open_readMode(pathname);
    //open_writeMode(pathname);
    //open_lseek(pathname2);
    standard_io("hello, standard io, welcome to code world!n");
    return 0;
}

void open_readMode(const char *pathname)
{
    int fd;
    char buf[1024] = {0};
    const char *buf2 = "is omp";

    
    
    fd = open(pathname, O_RDONLY);

    if (fd < 0)
 printf("open errorn");

    
    
    if (read(fd, buf, sizeof(buf)) < 0)
 printf("read errorn");

    printf("------after read------n");
    printf("%sn", buf);

    if (write(fd, buf2, sizeof(buf2)) < 0)
 printf("write errorn");

    printf("------after write-----n");
    printf("%sn", buf);

    close(fd);    
    exit(0);
}

void open_writeMode(const char *pathname)
{
    int fd;
    char buf[1024] = {0};
    const char *buf2 = "this is O_WRONLY";

    fd = open(pathname, O_WRONLY);

    if (fd < 0)
 printf("open errorn");
    if (read(fd, buf, sizeof(buf)) < 0)
 printf("read errorn");

    printf("------after read------n");
    printf("%sn", buf);

    if (write(fd, buf2, sizeof(buf2)) < 0)
 printf("write errorn");

    printf("------after write-----n");
    printf("%sn", buf);
}


void open_lseek(const char *pathname)
{
    int fd;
    char buf[256] = {0};
    char buf2[] = "this is a hole";

    int prepos;
    off_t currpos;  

    
    fd = open(pathname, O_RDWR);
    if (fd < 0)
 printf("open errorn");

    if (read(fd, buf, sizeof(buf)) < 0)
 printf("read errorn");

    
    prepos = strlen(buf);
    
    currpos = lseek(fd, 8, SEEK_CUR);
    
    printf("prepos=%lu, currpos=%lld", strlen(buf), currpos);

    
    ssize_t write_ret;
    write_ret = write(fd, buf2, sizeof(buf2));    
    printf("write_ret = %zdn", write_ret);    
    if (write_ret < 0)
    {
 printf("write errorn");
    }
}



void standard_io(const char *ptr_input)
{
    int n;
    char buf[1024] = {0};

    printf("%sn", ptr_input);
    while ((n = read(STDIN_FILENO, buf, 1024)) > 0)
    {
 if (write(STDOUT_FILENO, buf, n) != n)
 {
     printf("write to stdout errorn");
 }
    }

    if (n < 0)
    {
 printf("read from stdin errorn");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/233665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号