ubuntu学习(四)----文件写入操作编程

1、write函数的详解

ssize_t write(int fd,const void*buf,size_t count);

参数说明:

fd:是文件描述符(write所对应的是写,即就是1)

buf:通常是一个字符串,需要写入的字符串

count:是每次写入的字节数

返回值:

成功:返回写入的字节数

失败:返回-1并设置errno

ps: 写常规文件时,write的返回值通常等于请求写的字节 数count, 而向终端设备或者网络写时则不一定

2、write函数使用

首先打开终端,输入

man 2 write

接着打开新的终端,输入:

vi demo3.c

输入如下代码:

cpp 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
int main()
{

    int fd; 
    char *buf = "asdfggh";
    fd = open("./file1",O_RDWR);
    if(fd == -1){
        printf("open file1 failed\n");
        fd = open("./file1",O_RDWR|O_CREAT,0600);
        if(fd>0){
             printf("create file1 success\n");  
      
        }
    }

    printf("open susceess : fd = %d\n",fd);
    write(fd,buf,strlen(buf));
    close(fd);

    return 0;
}		

保存退出,接着输入如下:

vi demo3.c

./a.out

vi file1

相关推荐
花嫁代二娃3 小时前
Linux:环境变量
linux
数字芯片实验室4 小时前
分享一个可以学习正则表达式的网址:Pythex.org
学习·正则表达式
陈洪奇5 小时前
注册中心学习笔记整理
笔记·学习
光影少年5 小时前
从前端转go开发的学习路线
前端·学习·golang
l1x1n08 小时前
Vim 编辑器常用操作详解(新手快速上手指南)
linux·编辑器·vim
ajassi200010 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
o不ok!10 小时前
Linux面试问题-软件测试
linux·运维·服务器
fen_fen10 小时前
学习笔记(32):matplotlib绘制简单图表-数据分布图
笔记·学习·matplotlib
DaxiaLeeSuper10 小时前
Prometheus+Grafana+node_exporter监控linux服务器资源的方案
linux·grafana·prometheus
尽兴-11 小时前
如何将多个.sql文件合并成一个:Windows和Linux/Mac详细指南
linux·数据库·windows·sql·macos