
功能: 在文件中存储一个数字c 文件 读取0,该数字初始化为0;然后取出数字并将数字加3,然后再次写入文件;

预期结果: 文件中的数字初始化为0,可执行文件执行一次c 文件 读取0,并将数字更改为3;执行两次后,该数字将更改为6 ...



/*创建文件,存储值*/
# touch operation_log_id
/*文件内的值初始化为0*/
[root@localhost 20190613]# cat operation_log_id
0

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd = 0;
char acBuf[4096] = {0};
int i = 0;
fd = open("./operation_log_id", O_RDWR|O_ASYNC);
if(-1 == fd)
{
printf("error!\n");
return 0;
}
/*读取文件的值*/
int iR = 0;
while(iR = read(fd, acBuf, sizeof(acBuf)-1))
{
//printf("###%s\n", acBuf);
break;
}
/*清空文件*/
ftruncate(fd, 0);
/*重新设置文件的偏移量*/
lseek(fd, 0, SEEK_SET);
/*对读取出来的数字进行加3操作,atoi为字符串转换为整数的函数*/
sprintf(acBuf, "%d", atoi(acBuf)+3);
/*写入文件*/
write(fd, acBuf, strlen(acBuf));
close(fd);
return 0;
}
说明:
如果清空文件,请重置文件偏移. 数据将被覆盖;
否则,将清除文件并更新值. 如上所示.
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-246867-1.html
各种复杂添加剂