[文件操作]替换文件中的字符串
文件操作函数:
- int fseek(FILE *stream, long offset, int origin);
stream为文件指针
offset表示偏移量,正数表示正向偏移,负数表示负向偏移
origin文件从哪个位置开始偏移,可取值为SEEK_CUR, SEEK_END, SEEK_SET, 分别代表当前位置、文件结尾、文件开头。
- long ftell(FILE *stream);
当前文件位置指针相对于文件头的偏移字节数,使用fseek函数后,再调用ftell可以精确获取文件当前位置
- size_t fread(void *buffer, size_t size, size_t count, FILE *stream);
从文件流中读取数据count个项,每个项为size个字节,成功则返回读取到项的个数(<=count),不成功或者读到文件末尾则返回0
- fwrite
- fputs/fputc/fputchar
- fopen
- fclose
1 // BambooStrReplace.cpp : Defines the entry point for the console application. 2 // 3 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 8 #define BUFFER_SIZE 2048 //4096=4k 9 10 char *path = "C:\\...\\Makefile"; 11 12 const char *referStr = "ld_ar.mk"; 13 14 char srcStr[BUFFER_SIZE]; 15 char dstStr[BUFFER_SIZE]; 16 17 int main() 18 { 19 FILE *fp; 20 int ret; 21 22 // open file 23 fp = fopen(path, "rb+"); 24 if (fp == NULL) 25 { 26 printf("file open failed\n"); 27 return 0; 28 } 29 // goto file end 30 fseek(fp, 0, SEEK_END); 31 // back to 1kbytes 32 if (ftell(fp) > BUFFER_SIZE) 33 { 34 fseek(fp, -BUFFER_SIZE, SEEK_CUR); 35 } 36 else 37 { 38 fseek(fp, -ftell(fp), SEEK_CUR); 39 } 40 int filePosition = ftell(fp); 41 // clear str 42 memset(srcStr, 0, sizeof(srcStr)); 43 memset(dstStr, 0, sizeof(srcStr)); 44 45 // read file to array 46 ret = fread(srcStr, 1, BUFFER_SIZE, fp); 47 memcpy(dstStr, srcStr, ret); 48 // get ld_ar.mk position 49 char * dstPosition = strstr(srcStr, referStr); 50 int SecondOffset = (int)dstPosition - (int)srcStr; 51 // get " position 52 while (*dstPosition != '"') 53 { 54 dstPosition--; 55 } 56 int fisrtOffset = (int)dstPosition - (int)srcStr; 57 int deleteLen = SecondOffset - fisrtOffset; 58 59 dstStr[fisrtOffset + 1] = '.'; // add ".\" 60 dstStr[fisrtOffset + 2] = '\\'; 61 62 // delete string 63 for (int i = fisrtOffset; i < ret - deleteLen; i++) 64 { 65 dstStr[i+3] = srcStr[i + deleteLen]; 66 } 67 for (int i = ret - deleteLen; i < ret; i++) 68 { 69 dstStr[i] = '\0'; 70 } 71 // put into Makefile 72 fseek(fp, filePosition, SEEK_SET); 73 fputs(dstStr, fp); 74 fclose(fp); 75 //system("pause"); 76 return 0; 77 }