I'd like to ask you a question about writing code that saves upside down using C language file processing

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

#include <stdio.h>
#include <string.h>

int main(void) {
  float f[3];
  scanf("%f %f %f", f, f+1, f+2);

  FILE *w_file;
  w_file = fopen("text.tx", "w");
  // write text initialize to file size 0
  fprintf(w_file, "%f %f %f\n", f[0], f[1], f[2]);
  fclose(w_file);

  float rf[3];
  FILE *r_file;
  r_file = fopen("text.tx", "r");
  //r read text
  fscanf(r_file, "%f %f %f", rf, rf+1, rf+2);
  fclose(r_file);
  printf("r_file: %f %f %f\n", rf[0], rf[1], rf[2]);

  FILE *a_file;
  a_file = fopen("text.tx", "a");
  //a add append / Start at the end of the file
  fprintf(a_file, "a for append.\n");
  fclose(a_file);

  //r+, w+, w+r, r+w: text read/write
  //rb+, wb+ binary read/write

  //fgetc, fputc, EOF
  FILE *fgetc_file, *fputc_file;
  fgetc_file = fopen("text.tx", "r");
  fputc_file = fopen("fputc.tx", "w");
  char ch; 
  ch = fgetc(fgetc_file); // Read by 1byte
  while(ch != EOF){ // End Of File
    printf("%c", ch);
    fputc(ch, fputc_file);
    ch = fgetc(fgetc_file);
  }
  fclose(fgetc_file);
  fclose(fputc_file);

  // Write a code that reads fputc.tx and stores the text value upside down in back.tx

  FILE *b_file;

  char temp[64], temp1[64];
  int i, size;

  fputc_file = fopen("fputc.tx", "r");
  b_file = fopen("back.tx", "w");

  for(;;){
    fgets(temp, 254, fputc_file);
    if(feof(fputc_file)) break;
    size = (int)strlen(temp);

    for(i = size-1; i >= 0; i--)
      temp1[size-1-i] = temp[i-1];
    temp1[size-1] = '\0';
    fputs(temp1, b_file);
    fputs("\n", b_file);
  }

  fclose(fputc_file);
  fclose(b_file);

  return 0;
}

If you run the code above,

1 2 3
000000.3 000000.2 000000.1
.dneppa rof a

It's printed out like this.

I don't know how to change the order of 000000.3000000.2000000.1 and .dneppa rofa.

I wonder how I can fix it to get the results like above.

c

2022-09-20 13:14

1 Answers

Simply make the input a string of sprintf() and save it to a file in reverse order.

char buff[1024] = {};
sprintf(buff, "%f %f %f\n", f[0], f[1], f[2]);
sprintf(buff, "a for append.\n");

Through the above code, buff stores the following:

1.000000 2.000000 3.000000
a for append.

Now, if we reverse this, we'll do the following.

int i;
int length = strlen(buff);
for (i = length - 1; i >= 0; --i) {
    buff[i];
}

Through the for statement above, dneppa rof ...I'm going to circle the string in the same way as right?

Then you can save it to a file in this order to get the results you want:

fputc((unsigned char) buff[i], b_file);


2022-09-20 13:14

If you have any answers or tips


© 2022 pinfo. All rights reserved.