Language/C
[따배씨] 13.4 텍스트 파일 모드 스트링과 다양한 입출력 함수들
migrationArc
2021. 6. 18. 17:47
따배씨 - 따라하며 배우는 C언어
13강 파일 입출력
13.4 텍스트 파일 모드 스트링과 다양한 입출력 함수들
- fprintf()
- fscanf()
- fgets()
- fputs()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 31
int main(void){
FILE * fp;
char words[MAX] = {'\0'};
const char* filename = "record.txt";
/*
fopne() mode strings for text fiels
- r : reading
- w : creating-and-writing or over-writing
- a : appending or creating-and-writing
- r+ : both rading and writing
- w+ : reading writing, over-writin or crating
- a+ : reading and writing, appending or creating
*/
if ((fp = fopen(filename, "a+")) == NULL)
{
fprintf(stderr, "Can't open \"%s\" file.\n", filename);
exit(EXIT_FAILURE);
}
while((fscanf(stdin, "%30s", words) != NULL) && (words[0] != '.'))
fprintf(fp, "%s\n", words);
rewind(fp); /* go back to begining of file*/
while (fscanf(fp, "%s", words) == 1)// while (fscanf(fp, "%s", words) != EOF)
fprintf(stdout, "%s\n", words);
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
return 0;
}
fprintf(stderr, "Can't open \"%s\" file.\n", filename);
- stderr 에 출력을 하여도 stdout 과 같이 동작
- 구분하여 동작하게 하려면 운영체제에서 redirection 할때 error 로 출력하게 해주어야 함
while((fscanf(stdin, "%30s", words) != NULL) && (words[0] != '.'))
fprintf(fp, "%s\n", words);
fscanf(stdin, "%30s", words) != NULL
- EOF check
while((fgets(words, MAX, stdin) != NULL) && (words[0] != '.'))
fputs(words, fp);
- fgets()
rewind(fp); /* go back to begining of file*/
- 파일의 처음으로 돌아감
while (fscanf(fp, "%s", words) == 1)// while (fscanf(fp, "%s", words) != EOF)
fprintf(stdout, "%s\n", words);
fscanf(fp, "%s", words) == 1
- EOF check
while (fgets(words, MAX, fp) != NULL)// EOF check
fputs(words, stdout);
- fgets()
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com