본문 바로가기
728x90
반응형
SMALL

programming376

chapter 18) 버퍼를 공유함으로 인해 발생하는 문제 #include int main(void){ FILE *fp; int age; char name[20]; fp = fopen("a.txt", "r"); fscanf(fp, "%d", &age); fgets(name, sizeof(name), fp); // 오류 발생 printf("age : %d, name : %s", age, name); fclose(fp); return 0; } ### 파일 열기 - `FILE *fp;`는 파일 포인터 `fp`를 선언합니다. 이 포인터는 파일을 다루는 데 사용됩니다. - `fp = fopen("a.txt", "r");`를 통해 "a.txt" 파일을 읽기 모드로 엽니다. 파일이 성공적으로 열리면 `fp`는 열린 파일을 가리키게 됩니다. ### 파일로부터 데이터 읽기 - .. 2024. 10. 11.
chapter 18) 문자열을 한 문자씩 파일로 출력하기 #include int main(void){ FILE *fp; char str[] = "banana"; int i; fp = fopen("b.txt", "w"); if (fp == NULL){ printf("do not open the file.\n"); return 1; } i = 0; while(str[i] != '\0'){ fputc(str[i], fp); i++; } fputc('\n', fp); fclose(fp); return 0; } ### 코드 분석 - `FILE *fp;`는 파일 작업을 위한 파일 포인터 `fp`를 선언합니다. - `char str[] = "banana";`는 쓸 문자열을 저장하는 `str` 배열을 선언하고 "banana"로 초기화합니다. - `fp = fopen("b.t.. 2024. 10. 10.
chapter 18) 다양한 자료형을 형식에 맞게 입출력 #include int main(void){ FILE *ifp, *ofp; char name[20]; int kor, eng, math; int total; double avg; int res; ifp = fopen("a.txt", "r"); if (ifp == NULL){ printf("do not make the file.\n"); return 1; } ofp = fopen("b.txt", "w"); if (ofp == NULL){ printf("do not openn the file.\n"); return 1; } while(1){ res = fscanf(ifp, "%s%d%d%d", name, &kor, &eng, &math); if (res == EOF) break; total = kor + e.. 2024. 10. 9.
chapter 18) stdin과 stdout을 사용한 문자 입출력 #include int main(void){ int ch; while(1){ ch = fgetc(stdin); if (ch == EOF){ break; }fputc(ch, stdout); } return 0; } ### 코드 설명 - `int ch;`: 입력받은 문자를 저장하기 위한 정수형 변수 `ch`를 선언합니다. 여기서 `int` 타입을 사용하는 이유는 `EOF`를 처리하기 위함입니다. `EOF`는 일반적으로 `-1`로 정의되며, `char` 타입으로는 이 값을 표현할 수 없습니다. - `while(1) { ... }`: 무한 루프를 생성합니다. 이 루프는 `EOF`가 입력될 때까지 계속 실행됩니다. - `ch = fgetc(stdin);`: `fgetc` 함수를 사용하여 표준 입력으로부터 한 문자.. 2024. 10. 8.
728x90
반응형
LIST