如何修改txt文件中某个位置的数据?
比如ma.txt中有如下内容:
thickness厚度u1u2a0a1
0.19-0.1990.20.115-5-2
0.20-0.2090.1960.1145-5-2
我想修改成;
比如ma.txt中有如下内容:
thickness厚度u1u2a0a1
0.19-0.1990.190.11-4-1.8
0.20-0.2090.180.10-4-1.8
[解决办法]
如果修改前后的数据字节数是一样的,直接seek到要修改的地方write就行了
如果字节数不一样,只能重写一个文件,然后删掉原来的
[解决办法]
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_LEN 20#define ARR_LEN 50struct st_strdata{ char thickness[MAX_LEN]; char u1[MAX_LEN]; char u2[MAX_LEN]; char a0[MAX_LEN]; char a1[MAX_LEN];};int main(){ int nRes = 0; int i = 0; int iCount = 0; struct st_strdata sdata[ARR_LEN] = {0}; FILE* fp = fopen("ma.txt", "r"); i = 0; iCount = 0; while(1) { nRes = fscanf(fp, "%s%s%s%s%s", sdata[i].thickness, &sdata[i].u1, &sdata[i].u2, &sdata[i].a0, &sdata[i].a1); ++iCount; ++i; if(-1 == nRes) { break; } } fclose(fp); printf("原数据: \n"); for(i = 0; i <iCount; ++i) { printf("%s %s %s %s %s\n", sdata[i].thickness, sdata[i].u1, sdata[i].u2, sdata[i].a0, sdata[i].a1); } printf("\n"); fp = fopen("ma.txt", "w"); for(i = 0; i <iCount; ++i) { if(0 == strcmp(sdata[i].u1, "u1")) { fprintf(fp, "%s %s %s %s %s\n", sdata[i].thickness, sdata[i].u1, sdata[i].u2, sdata[i].a0, sdata[i].a1); continue; } if (0 == strcmp(sdata[i].thickness, "0.19-0.199")) { if (0 == strcmp(sdata[i].u1, "0.2")) { strcpy(sdata[i].u1, "0.19"); } if (0 == strcmp(sdata[i].u2, "0.115")) { strcpy(sdata[i].u2, "0.11"); } if (0 == strcmp(sdata[i].a0, "-5")) { strcpy(sdata[i].a0, "-4"); } if (0 == strcmp(sdata[i].a1, "-2")) { strcpy(sdata[i].a1, "-1.8"); } } if (0 == strcmp(sdata[i].thickness, "0.20-0.209")) { if (0 == strcmp(sdata[i].u1, "0.196")) { strcpy(sdata[i].u1, "0.18"); } if (0 == strcmp(sdata[i].u2, "0.1145")) { strcpy(sdata[i].u2, "0.10"); } if (0 == strcmp(sdata[i].a0, "-5")) { strcpy(sdata[i].a0, "-4"); } if (0 == strcmp(sdata[i].a1, "-2")) { strcpy(sdata[i].a1, "-1.8"); } } fprintf(fp, "%s %s %s %s %s\n", sdata[i].thickness, sdata[i].u1, sdata[i].u2, sdata[i].a0, sdata[i].a1); } fclose(fp); return 0;}
[解决办法]
如果文件内容不是很多的话
也可以把文件的内容都读出来,修改之后再全部写进去