Linux系统编程(二)文件I/O操作

        程序编写
调用open()系统调用打开一个叫做test.txt的文件(如果不存在则会创建该文件),然后调用write()系统调用该字符串MSG_STR写入到该文件中,之后调用read()系统调用读出该文件里的内容。

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

#define BUFSIZE 1024
#define MSG_STR "Hello World!\n"

int main(int argc, char *argv[])
{
        int fd = -1;
        int rv = -1;
        char buf[BUFSIZE];

        fd=open("test.txt",O_RDWR|O_CREAT|O_TRUNC,0666);
        if(fd < 0)
        {
                perror("Open/Create file test.txt failure");
                return 0;
        }
        printf("Open file returned file descriptor [%d]\n", fd);

        if((rv=write(fd,MSG_STR, strlen(MSG_STR))) < 0)
        {
                printf("Write %d bytes into file failure: %s\n", rv, strerror(errno));
                goto cleanup;
        }

        //memset(buf, 0, sizeof(buf));
        if((rv=read(fd, buf, sizeof(buf))) < 0)
        {
                printf("Read data from file failure: %s\n",strerror(errno));
                goto cleanup;
        }

        printf("Read %d bytes data from file: %s\n", rv, buf);

cleanup:
        close(fd);
        
        return 0;
}

gcc编译运行

笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值