c语言 对文件操纵

[复制链接]
发表于 2025-9-30 01:00:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
c语言 对文件操纵

1、打开./ipc_test/dev.txt文件,在第1行 覆盖写入"MAC=1q23456789"
  
代码
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. int main() {
  6.     const char *line_1 = "MAC=1q23456789\n"; // 要写入的内容(含换行符)
  7.     int fd;
  8.     // 打开文件(覆盖写入模式,若文件不存在则创建)
  9.     /***
  10.         C 语言中,open 函数是用于打开文件的系统调用,主要用于 低级文件操作。
  11.         它定义在头文件 <fcntl.h> 中
  12.         (有时也需要 <unistd.h> 进行后续操作如 read、write 和 close)
  13.     **/
  14.     // 如果出错,open 返回 -1,并设置 errno。
  15.     fd = open("./ipc_test/dev.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
  16.    
  17.     if (fd == -1)
  18.     {
  19.         perror("open ./ipc_test/dev.txt failed");
  20.         return -1;
  21.     }
  22.     // 写入内容
  23.    /***write函数原型ssize_t write(int fd, const void *buf, size_t count);
  24.    
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表