C language implementation to modify the text file in particular lines of implementation code

  • 2020-04-02 01:10:29
  • OfStack

Ok, first I will describe the functional requirements:
It's simply the C implementation of the sed command in the Shell, which locates the line of the required field and then modifies it to the required content. However, since C language is a process-oriented language and requires sequential execution, there are many difficulties in the implementation. Here, the blogger describes the implementation process as follows for your reference.

Problem description:

Text content:


wireless.1.authmode=1
wireless.1.compression=0
wireless.1.current_ap=ssid12
wireless.1.current_state=1
wireless.1.devname=ath0
wireless.1.enable_slave1_status=disabled
wireless.1.enable_slave2_status=disabled
wireless.1.enable_slave3_status=disabled

All I need to do is change the fourth line to read:


wireless.1.current_state=0

The problem seems simple, but the realization process takes a lot of trouble...

Here I give the implementation code, the comments have been added to the code:



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
int main()
{
 
 char linebuffer[512] = {0};
 char buffer1[512] = {0};
 char buffer2[512] = {0};

 int line_len = 0;
 int len = 0;
 int res;

 
 FILE *fp = fopen("cc.cfg", "r+");
 if(fp == NULL)
 {
  printf("open error");
  return -1;
 }
 while(fgets(linebuffer, 512, fp))
 {
  line_len = strlen(linebuffer);
  len += line_len;
  
  sscanf(linebuffer, "%[^=]=%[^=]", buffer1,buffer2);
  if(!strcmp("wireless.1.current_state", buffer1))
  {
   
   len -= strlen(linebuffer);
   
   res = fseek(fp, len, SEEK_SET);
   if(res < 0)
   {
    perror("fseek");
    return -1;
   }
   strcpy(buffer2, "=0");
   
   strcat(buffer1, buffer2);
   printf("%d",strlen(buffer1));
   
   fprintf(fp, "%s", buffer1);
   fclose(fp);
   return;
  }
 }
return 0;
}

Save the file name: my_sed. C

The operation effect is as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201306/201362510533158.gif" >

Let's look at the contents of the document:

 
wireless.1.authmode=1 
wireless.1.compression=0 
wireless.1.current_ap=ssid12 
wireless.1.current_state=0 
wireless.1.enable_slave1_status=disabled 
wireless.1.enable_slave2_status=disabled 
wireless.1.enable_slave3_status=disabled 


Realization principle:

The efficiency of this implementation is relatively high, because the contents of the entire file is not loaded into the buffer, but read line by line, until the match, then take advantage of the write file features, directly overwrite the written content can be, so as to complete the required function


Related articles: