- 论坛徽章:
- 1
|
请教对文件的写和内容替换操作?
呵呵,无事。自己练习了一下文件的读写。下面的代码仅供测试,健壮性极差,^_^。
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <string.h>;
- int main(void) {
- char buf[256],
- buf1[32],
- name[16],
- sex[8];
- int age,
- i,
- number;
- FILE *pin,
- *pout;
- memset(name,0x0,16);
- memset(sex,0x0,8);
- printf("Input value:");
- fflush(stdout);
- scanf("%s %d %s %d",name,&age,sex,&number);
- if ( ( pin = fopen("./in.txt","r") ) == NULL ) {
- printf("open infile error!\n");
- exit(1);
- }
- if ( ( pout = fopen("./out.txt","w") ) == NULL ) {
- printf("open outfile error!\n");
- exit(1);
- }
- memset(buf,0x0,256);
- memset(buf1,0x0,32*sizeof(int));
- fgets(buf,256,pin);
- while ( !feof(pin) ) {
- i = 0;
- while ( buf[i] != '=' ) {
- buf1[i] = buf[i];
- i++;
- }
- buf1[i] = '=';
- i++;
- if ( strcmp("name=",buf1) == 0 ) {
- sprintf(buf1+i,"%s",name);
- }
- else if ( strcmp("age=",buf1) == 0 ) {
- sprintf(buf1+i,"%d",age);
- }
- else if ( strcmp("sex=",buf1) == 0 ) {
- sprintf(buf1+i,"%s",sex);
- }
- else if ( strcmp("number=",buf1) == 0 ) {
- sprintf(buf1+i,"%d",number);
- }
- else {
- printf("input file error!\n");
- exit(1);
- }
- fputs(buf1,pout);
- fputc('\n',pout);
- memset(buf,0x0,256);
- memset(buf1,0x0,32*sizeof(int));
- fgets(buf,256,pin);
- }
- exit(0);
- }
复制代码 |
|