Linux C 读写文件

感受下C语言在Linux中读写文件用法,纯粹兴趣学习记录。

既然要读写文件,那肯定要使用Linux系统调用了,就是利用Linux系统提供的API进行函数调用,最终来实现文件读写。

操作文件通用步骤:

打开文件获取文件描述符
读写文件
关闭文件

上面有提到文件描述符,那什么是文件描述符?
当Linux系统打开一个文件的时候,会向程序返回一个非负整数,这个整数标识Linux系统打开的文件记录,通过这个整数就可以操作文件了。要是系统返回-1就表示打开失败了。

  • 打开文件获取文件描述符

int open(const char *pathname, int flags);

第一个参数代表文件名。
第二个表示文件访问模式有:
O_READ(只读)
O_WRONLY,(只写)
O_RDWR(读写)
返回参数就是文件描述符(file description)了

  • 读写文件

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

size_t是unsigned int 表示只能大于等于0
ssize_t是signed int 可以为正,可以为负

  • 关闭文件

int close(int fd);

说了半天没啥干货,直接上代码就明白了

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>

void readFile() {
        char s[] = "main.c";
        //只读打开文件
        int fd = open(s, O_RDONLY);

        if(fd == -1) {
                printf("error is %s\n", strerror(errno));
                return;
        }

        printf("sucess fd = %d\n", fd);
        char buf[100];
        memset(buf, 0, sizeof(buf));
        //read返回0表示文件读取完毕
        while(read(fd, buf, sizeof(buf) - 1) > 0) {
                printf("%s\n", buf);
                memset(buf, 0, sizeof(buf));
        }

        printf("%s\n", buf);
        //别忘记关闭
        close(fd);
}

void writeFile() {
        char s[] = "abc.txt";
        //读写并追加方式
        int fd = open(s, O_RDWR | O_APPEND);

        if(fd == -1) {
                //发生错误会把错误信息设置到errno中
                //通过strerror函数获取错误内容
                printf("error is %s\n", strerror(errno));
                return;
        }

        printf("sucess fd = %d\n", fd);
        char buf[100];
        memset(buf, 0, sizeof(buf));
        int i = 10;
        while(i-- > 0){
                strcpy(buf, "hello world linux write file \n");
                write(fd, buf, strlen(buf));
                memset(buf, 0, sizeof(buf));
        }

        close(fd);

}


int main(int arg, char *args[]) {
        readFile();
        writeFile();
        return 0;
}

要是不明白直接在linux系统中看man命令提供的帮助文档

man 2 read
man 2 write

Tip:
man 后面的2表示手册类型,因为read、write是Linux提供的系统调用(内核提供的函数),为了保证要查看的帮助是系统调用,所以指定手册类型为2。不加2的话有可能会查到可执行程序(shell命令)的用法。
还有一个常用的手册类型是3表示库函数调用(C程序库中的函数)

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux C语言中,读写配置文件通常使用INI文件格式。INI文件格式是一种简单的文本文件格式,其中键值对以节(section)的形式组织,并使用方括号([])将节名括起来。 以下是一个示例INI文件: ``` [Section1] key1=value1 key2=value2 [Section2] key3=value3 key4=value4 ``` 使用C语言读取INI文件的步骤如下: 1. 打开INI文件并读入内容。 2. 解析INI文件内容,将键值对存储到内存中的数据结构中。 3. 使用存储的键值对执行相应的操作。 以下是一个简单的例子: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE_LEN 1024 #define MAX_SECTION_LEN 256 #define MAX_KEY_LEN 256 #define MAX_VALUE_LEN 256 typedef struct { char section[MAX_SECTION_LEN]; char key[MAX_KEY_LEN]; char value[MAX_VALUE_LEN]; } config_item_t; int parse_config_file(const char* filename, config_item_t** items, int* count) { FILE* fp = fopen(filename, "r"); if (!fp) { return -1; } char line[MAX_LINE_LEN]; config_item_t* item = NULL; int item_count = 0; while (fgets(line, MAX_LINE_LEN, fp)) { // 去掉行末换行符 char* p = strchr(line, '\n'); if (p) *p = '\0'; // 去掉行首空格 p = line; while (*p == ' ') ++p; // 解析节 if (*p == '[') { char* q = strchr(p, ']'); if (!q) { fclose(fp); return -1; } *q = '\0'; item = NULL; continue; } // 解析键值对 if (item) { char* q = strchr(p, '='); if (!q) continue; // 忽略无效行 *q = '\0'; strcpy(item->key, p); strcpy(item->value, q + 1); ++item; } else { // 新建配置项 item = (config_item_t*)realloc(item, (item_count + 1) * sizeof(config_item_t)); if (!item) { fclose(fp); return -1; } strcpy(item->section, p); item->key[0] = '\0'; item->value[0] = '\0'; items[item_count++] = item; } } fclose(fp); *count = item_count; return 0; } void free_config_items(config_item_t** items, int count) { for (int i = 0; i < count; ++i) { free(items[i]); } free(items); } int main() { config_item_t* items[100]; int count = 0; if (parse_config_file("test.ini", items, &count) == 0) { for (int i = 0; i < count; ++i) { printf("[%s]\n", items[i]->section); printf("%s=%s\n", items[i]->key, items[i]->value); } } free_config_items(items, count); return 0; } ``` 该程序使用`parse_config_file`函数读取INI文件并解析内容,将每个节的键值对存储到一个`config_item_t`结构体中。最后,在`main`函数中遍历所有配置项并输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值