Supposons que le contenu de mon fichier test.config soit :
VITESSE=3
LONGUEUR=5
SCORE=8
NIVEAU=5
Utilisez les opérations sur les fichiers pour changer LENG=5 en LENG=3
L'idée de base pour implémenter cette fonction est la suivante :
1. Lisez le fichier de configuration dans le cache
2. strstr recherche la sous-chaîne pour trouver la position et recherche asdf = renvoie la position d'un
3. Position du pointeur + cheap (strlen("LENG="))
4. *p obtient le contenu, Assigned = modifié
5. L'opération d'écriture est un fichier et un caractère
#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)
{
char *readBuff = NULL;
int fdSrc;
if(argc != 2){ //./a.out test.config argc=2
printf("pararm error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR);
int size = lseek(fdSrc,0,SEEK_END);
readBuff =(char *)malloc(sizeof(char)*size+8);
lseek(fdSrc,0,SEEK_SET);
int n_read = read(fdSrc,readBuff,size);
char *p = strstr(readBuff,"LENG=");
if(p == NULL){
printf("not found\n");
exit(-1);
}
p = p + strlen("LENG=");
*p = '3'; //写入的是字符因此是''
lseek(fdSrc,0,SEEK_SET);
int n_write = write(fdSrc,readBuff,strlen(readBuff));
close(fdSrc);
return 0;
}