C基础常用代码

发布时间 2023-12-08 15:02:09作者: Hello-World3

1. 写文件

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

//write ASCII value
int file_write(char *fn, int val)
{
    int fd, ret;
    char buff[16] = {0};
    
    sprintf(buff, "%d", val); //change int to ASCII string val

    fd = open(fn, O_RDWR);
    if (fd < 0) {
        fprintf(stderr,"my_debug: open %s failed: %s\n", fn, strerror(errno));
        return -1;
    }
    ret = write(fd, buff, strlen(buff));
    if (ret < 0) {
        fprintf(stderr,"my_debug: write %s failed: %s\n", fn, strerror(errno));
        return -1;
    }
    close(fd);

    return 0;
}

void main()
{
    file_write("tmp.txt", 111);
}