本文已参与「新人创作礼」活动,一起开启掘金创作之路。
Linux文件编程练手项目
已经存在配置文件,名称为TEST.config,其内容如下:
SPEED=3 LENG=5 SCORE=9 LEVEL=5
现需要修改其内容,将SCORE的值修改为5
通过man手册查阅strstr函数的使用,如下所示:
NAME strstr, strcasestr - locate a substring
SYNOPSIS #include <string.h>
char *strstr(const char *haystack, const char *needle);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <string.h>
char *strcasestr(const char *haystack, const char *needle);
DESCRIPTION The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating null bytes ('\0') are not compared.
The strcasestr() function is like strstr(), but ignores the case of both
arguments.
RETURN VALUE These functions return a pointer to the beginning of the located substring, or NULL if the substring is not found.
代码实现如下所示:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc,char **argv)
{
int fdSrc;
char *readBuf=NULL;
if(argc!=2){
printf("参数传递错误\n");
exit(-1);
}
fdSrc=open(argv[1],O_RDWR);
int size=lseek(fdSrc,0,SEEK_END);
lseek(fdSrc,0,SEEK_SET);
readBuf=(char *)malloc(sizeof(char)*size+8);
int n_read=read(fdSrc,readBuf,size);
char *p=strstr(readBuf,"SCORE=");
if(p==NULL){
printf("not found!!!\n");
exit(-1);
}
p=p+strlen("SCORE=");
*p = '5';
lseek(fdSrc,0,SEEK_SET);//此处需注意将光标回到开始位置
int n_write=write(fdSrc,readBuf,strlen(readBuf));
close(fdSrc);
return 0;
}
执行结果如图所示:
1 .没有执行前
2.执行代码:
3.查看执行后的文件内容
4.结果如下:
Linux文件编程之fputc,fgetc,feof函数的使用
通过一个例子来熟悉使用三个函数
fputc函数原型
int fputc(int c, FILE *stream);
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
int i;
char *str="I Love you the way you are!\n";
fp=fopen("./test.txt","w+");
int len=strlen(str);
for(i=0;i<len;i++)
{
fputc(*str,fp);
str++;
}
fclose(fp);
return 0;
}
fgetc与feof函数原型
int fgetc(FILE *stream);
int feof(FILE *stream);
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char c;
fp = fopen("./test.txt","r");
//当feof的返回值为非0值说明到达文件末尾了
while(!feof(fp))
{
c = fgetc(fp);
printf("%c",c);
}
fclose(fp);
return 0;
}
补充:写结构体数组到文件中
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
struct Test
{
int a;
char c;
};
int main()
{
FILE *fp;
struct Test data[2]={{100,'a'},{101,'c'}};
struct Test data2[2];
fp=fopen("./file1","w+");
int n_write=fwrite(&data,sizeof(struct Test)*2,1,fp);
fseek(fp,0,SEEK_SET);
int n_read=fread(&data2,sizeof(struct Test)*2,1,fp);
printf("read %d,%c\n",data2[0].a,data[0].c);
printf("read %d,%c\n",data2[1].a,data[1].c);
fclose(fp);
return 0;
}