Linux系统编程3–修改和写入文件
1、配置文件的修改
-
SPEED = 5; LENG = 100; SCORE = 90; LEVEL = 95;
我想把修改Linux
系统里面某个文件里的内容修改一些
1.1、所需工具
defconfig
文件和.config
文件都是linux
内核的配置文件
-
先再
Linux
系统底下创建一个文件:TEST.config
SPEED=3 LENG=3 SCORE=9 LEVEL=5
-
利用
strstr
函数—查找函数
//C 库函数,查询
char *strstr(const char *haystack, const char *needle)
//在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 '\0'。
-
- haystack – 要被检索的 C 字符串。
-
- needle – 在 haystack 字符串内要搜索的小字符串。
-
- 返回值:该函数返回在 haystack 中第一次出现 needle 字符串的位置(该字符串前面),如果未找到则返回 null。
1.2、程序演示
//demo.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int fdSrc; //源fd
char *readBuf = NULL;
if(argc != 2)//参数不为3,终止程序;
{
printf("pararm error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR); //a、打开scr.c
int size = lseek(fdSrc, 0, SEEK_END);
//计算源fd 大小
lseek(fdSrc,0,SEEK_SET);
//光标返回至文件头
readBuf = (char *)malloc(sizeof(char)*size +8);
int n_read = read(fdSrc,readBuf,size); //b、读scr 到 buf
char *p = strstr(readBuf,"LENG=");
if(p == NULL)
{
printf("not found\n");
exit(-1);
}
p = p+strlen("LENG=");
*p = '5';
lseek(fdSrc,0,SEEK_SET);
//光标返回至文件头
int n_write = write(fdSrc,readBuf,strlen(readBuf)); //d、将 buf 写入到 des
close(fdSrc); //e、关闭两个文件
return 0;
}
TEST.config
SPEED=3
LENG=5
SCORE=9
LEVEL=5
2、写入文件
2.1、写入一个结构体到文件
ssize_t write(int fd, const void *buf, size_t count); //写入
ssize_t read(int fd, void *buf, size_t count); //读取
buf
可以为字符串,也可以是地址,字符串也可以理解为地址
- 已有文件
//file1
NULL
- 演示
//demo2.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
int a;
char c;
};
int main()
{
int fd;
struct Test data = {100,'a'};
struct Test data2;
fd = open("./file1",O_RDWR);
int n_write = write(fd,&data,sizeof(struct Test));
lseek(fd,0,SEEK_SET);
int n_read = read(fd, &data2,sizeof(struct Test));
printf("read %d,%c \n",data2.a,data2.c);
close(fd);
return 0;
}
//file1
d^@^@^@a^@^@^@ //编码问题
编码问题可以忽略,人类看不懂,对计算机理解没问题
2.2 写入一个结构体数组到文件
- 已有文件
//file1
d^@^@^@a^@^@^@
- 演示
//demo3.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
int a;
char c;
};
int main()
{
int fd;
struct Test data[2] = {{100,'a'},{101,'b'}}; //结构体数组
struct Test data2[2];
fd = open("./file1",O_RDWR);
int n_write = write(fd,&data,sizeof(struct Test)*2);//大小*2
lseek(fd,0,SEEK_SET);
int n_read = read(fd, &data2,sizeof(struct Test)*2);
printf("read %d,%c \n",data2[0].a,data2[0].c);
printf("read %d,%c \n",data2[1].a,data2[1].c);
close(fd);
return 0;
}
//file1
d^@^@^@a^@^@^@e^@^@^@b^@^@^@
- 编码问题可以忽略,人类看不懂,对计算机理解没问题
欢迎大家一起交流讨论!