C언어 파일 처리를 이용한 거꾸로 저장하는 코드 작성 질문드립니다
조회수 975회
#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");
// w write text 파일 크기 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 append 추가 / 파일의 끝에서 시작
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); // 1byte씩 읽어옴
while(ch != EOF){ // End Of File
printf("%c", ch);
fputc(ch, fputc_file);
ch = fgetc(fgetc_file);
}
fclose(fgetc_file);
fclose(fputc_file);
// fputc.tx를 읽어와서, text 값을 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;
}
위 코드를 실행해보면
입력
1 2 3
현재 출력 결과
000000.3 000000.2 000000.1
.dneppa rof a
이렇게 출력이 되는데
000000.3 000000.2 000000.1 과 .dneppa rof a 의 순서를 어떻게 바꿔야 할지 모르겠습니다.
원하는 출력 결과
.dneppa rof a
000000.3 000000.2 000000.1
어떻게 고쳐야 위처럼 결과가 나올 수 있는지 궁금합니다.
1 답변
-
간단하게 입력을 sprintf()으로 문자열로 만든 후 역순으로 파일에 저장하면 되겠네요.
char buff[1024] = {}; sprintf(buff, "%f %f %f\n", f[0], f[1], f[2]); sprintf(buff, "a for append.\n");
위 코드를 통해
buff
에는 다음과 같은 내용이 저장됩니다.1.000000 2.000000 3.000000 a for append.
이제 이걸 역순으로 순회하면 다음과 같겠죠.
int i; int length = strlen(buff); for (i = length - 1; i >= 0; --i) { buff[i]; }
위
for
문을 통해 .dneppa rof ... 와 같은식으로 문자열을 순회 하겠죠?그럼 이 순서로 다음과 같이 파일에 저장하면 원하시는 결과를 얻을 수 있습니다.
fputc((unsigned char) buff[i], b_file);
댓글 입력