문자열이 저장된 파일의 내용을 ' '(공백)을 delimeter로 사용하여 단어별로 개행한 파일에 Buffered I/O를 이용하여 저장하는 프로그램을 작성하시오.
다섯 번째 과제는 Buffered I/O를 사용하여 파일의 내용을 단어별로 나누어 저장하는 것이다.
fgets
, fputs
, fopen
, fclose
와 같은 파일 입출력 함수를 사용하여 과제를 수행한다.
int fputs(const char *str, FILE *stream);
문자열을 파일에 쓰기 위해 사용하는 함수이며 원형은 위와 같다.
str
: 파일에 쓸 문자열이다.stream
: 문자열을 쓸 파일의 파일 포인터이다.\n
을 추가해서 쓰거나 fputc
를 이용하여 개행 문자를 써야 한다."My name is Dohyun Kim" 문장을 작성하고 저장한다.
fopen
으로 input.txt 파일을 읽기 모드로 열고 output.txt 파일을 쓰기 모드로 연다. 이때, output.txt 파일이 없어도 자동으로 생성된다. 각각의 파일 포인터(in_fp
와 out_fp
)를 이용하여 입력 파일과 출력 파일을 가리킨다. const char* input_file = "input.txt";
const char* output_file = "output.txt";
FILE* in_fp = fopen(input_file, "r");
FILE* out_fp = fopen(output_file, "w");
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main() {
const char* input_file = "input.txt";
const char* output_file = "output.txt";
FILE* in_fp = fopen(input_file, "r");
FILE* out_fp = fopen(output_file, "w");
if (in_fp == NULL || out_fp == NULL) {
perror("cannot open this file");
exit(1);
}
char buffer[BUFFER_SIZE];
while (fgets(buffer, BUFFER_SIZE, in_fp) != NULL) {
char* token = strtok(buffer, " ");
while (token != NULL) {
fputs(token, out_fp);
fputc('\n', out_fp);
token = strtok(NULL, " ");
}
}
fclose(in_fp);
fclose(out_fp);
return 0;
}