C언어 stdio.h 파일입출력
fopen
fopen은 파일을 열때 사용하는 것으로 읽기모드나 쓰기모드등으로 열수 있다
ex. fopen(자신이 열고자 하는 파일 이름, 읽기모드나 쓰기모드)
1 2 3 4 5 6 7 | #include <stdio.h> #include <string.h> int main(void){ FILE *f = fopen("test.txt","w"); return 0; } | cs |
test.txt라는 파일을 읽기 모드로 열기
1 2 3 4 5 6 7 | #include <stdio.h> #include <string.h> int main(void){ FILE *f = fopen("test.txt","r"); return 0; } | cs |
test.txt라는 파일을 읽기 모드로 열기
fprintf는 파일의 내용을 채우는 함수입니다.
1 2 3 4 5 6 7 8 9 | #include <stdio.h> #include <string.h> int main(void){ FILE *f = fopen("test.txt","r"); fprintf(f,"HELLO WORLD"); fclose(f); return 0; } | cs |
위의 예제는 test.txt라는 파일을 열고 그 파일안에 HELLO WORLD를 넣는 것입니다.
그리고 fclose는 파일을 닫겠다라는 뜻입니다.
fscanf는 파일의 내용을 얻어오는 함수입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> #include <string.h> int main(void){ FILE *f = fopen("test.txt","r"); char str1[16]; char str2[16]; fscanf(f,"%s%s",str1,str2); printf("%s %s",str1,str2); fclose(f); return 0; } | cs |
위의 예제는 test.txt라는 파일을 열어서 fscanf를 통해 str1과 str2를 채워줍니다. 그리고 printf를 통해 파일안에 있는것을 출력할수가 있습니다.
'C언어' 카테고리의 다른 글
stdlib.h 1 (0) | 2018.06.11 |
---|---|
rand함수 사용하기 (0) | 2018.06.11 |
C언어 string.h 3번째 (0) | 2018.06.05 |
C언어 string.h2 (0) | 2018.06.05 |
C언어 string.h (0) | 2018.06.05 |