Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c - File read write to same file?

I've managed to open a file and read while writing to another file with var=fopen(file,"r") / "w" but even with r+ or w+ moded I can't open a file and alter its contents.

Imagine this:

int formatacao (char original[]){/*se a cadeia nao tiver escrita em maiusculas, esta fun?ao vai alteralas para tal*/
    int val1;
    FILE * original_open;

    original_open = fopen (original,"r+");

    if (original_open==0){
       printf ("ficheiro %c 1.",original);
    }


    while ((val1=fgetc(original_open))!=EOF){
          if (val1>='a'&&val1<='z'&&val1){
             fputc(val1-32,original_open);
          }
          else 
          fputc(val1,original_open);
    }

    fclose (original_open);
    return (0);
}

Code works, no errors, no warning, only problem is: it erases the contents on the file if I use it like this BUT this works:

int main (){
    int val1,val2,nr=0;
    FILE* fp1;
    FILE* fp2;
    fp1=fopen ("DNAexample.txt","r");
    fp2=fopen ("DNAexample1.txt","w");
    if (fp1==0){
       printf ("EPIC FAIL no 1.
");
    }
    while ((val1=fgetc(fp1))!=EOF){
          if (val1>='a'&&val1<='z'&&val1){
             fputc(val1-32,fp2);
          }
          else 
          fputc(val1,fp2);
    }


    fclose (fp1);
    fclose (fp2);
    return (0);
}

Flawlessly! How can I open a file, read char by char and decide if I want to change the char or not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to intervene a file positioning function between output and input unless EOF was found on input.

This works for me:

#include <stdio.h>

int formatacao (char *original) {
  int val1;
  FILE *original_open;
  int write_at, read_at;

  original_open = fopen(original, "r+");
  if (original_open == 0) {
    printf("ficheiro %s
", original);
  }
  write_at = read_at = 0;
  while ((val1 = fgetc(original_open)) != EOF) {
    read_at = ftell(original_open);
    fseek(original_open, write_at, SEEK_SET);
    if (('a' <= val1) && (val1 <= 'z')) {
      fputc(val1 - 32, original_open);
    } else {
      fputc(val1, original_open);
    }
    write_at = ftell(original_open);
    fseek(original_open, read_at, SEEK_SET);
  }
  fclose(original_open);
  return (0);
}

int main(void) {
  formatacao("5787867.txt");
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...