C基础常用代码

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);
}

 

2. 读文件

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

int file_read(char *fn)
{
    int fd, ret;
    ssize_t count = 0;
    char buff[257];

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

    do {
        int ret = read(fd, buff, sizeof(buff)-1);
        if (!ret) break;
        count += ret;
        buff[ret] = 0;
        printf("%s", buff);
    } while (ret);
    printf("data count=%ld\n", count);
    
}

int main()
{
    file_read("tmp.txt");
    return 0;
}

 

3. 使用信号

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void sig_handler(int sig)
{
    printf("sig=%d\n", sig);
    return;
}

int main() {
    if (signal(SIGCHLD, sig_handler) == SIG_ERR) {
        printf("signal error");
    }
    printf("Parent loop\n"); 
    while (1) sleep(1); 
}

 

posted on 2023-12-08 15:00  Hello-World3  阅读(39)  评论(0编辑  收藏  举报

导航