Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File read write to same file?

Tags:

c

file

io

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.\n");
    }
    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?

like image 284
DaRk_f0x Avatar asked Apr 26 '11 08:04

DaRk_f0x


2 Answers

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\n", 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;
}
like image 176
pmg Avatar answered Oct 10 '22 10:10

pmg


Open the file with 'a+' option, in order to append to the file:

fopen ("DNAexample.txt","a+");

w+ will erase your file if exists or create new if the specified doesn't exist. a+ will open the existing file and you will be able to edit it.

You can read more about file operations here: http://www.functionx.com/cppbcb/cfileprocessing.htm

like image 42
anthares Avatar answered Oct 10 '22 12:10

anthares