본문 바로가기
C/☞

[62] File IO

by TR. 2020. 7. 27.

File Input and Output

 

0. 파일위치 (프로젝트 위치)

FILE* file;

 

1. 파일쓰기 (write text 모드)    

fopen_s(&file, "파일명", "wt") 

fputs("저장할문자열", file)

fclose(file)

 

2. 파일읽기 (read text 모드)

fopen_s(&file, "파일명", "rt")

fgets(저장할변수, 읽기사이즈, 파일위치)

 fclose(file)

* fgets() 함수는 텍스트를 한 줄씩 읽어옴 ("\n"포함)

 

 

# define _CRT_SECURE_NO_WARNING

# include <Windows.h>
# include <stdio.h>
# include <string.h>
# include <stdlib.h>

void main() {
	// File IO
	FILE* file;					// 저장 메모리 위치 (프로젝트 위치)

	// 1. 쓰기
	fopen_s(&file, "test.txt", "wt");
	fputs("Do not gentle.", file);
	fclose(file);

	// 2. 읽기
	fopen_s(&file, "test.txt", "rt");
	char data[100];
	fgets(data, 100, file);				// 한 줄 읽어오기 
	fclose(file);

	printf("data : %s\n", data);



	system("pause");
}

 

fopen()

더보기
# include <stdio.h>
# include <stdlib.h>
# include <string.h>

int main(){
    
    FILE* file;
    
    char* data = new char[100];
    // char data[100];

    printf("입력 : ");
    scanf("%s", data);
    printf("input : %s\n", data);

    // 파일쓰기
    file = fopen("test.txt", "wt");
    fputs(data, file);
    fclose(file);
    printf("file saved >>\n");
    
    // 파일읽기
    fopen("test.txt", "rt");
    fgets(data, 20, file);
    printf("file loaded >>\n");
    printf("data : %s\n", data);
    fclose(file);


    return 0;
}

 


파일에서 여러줄 읽어오기

 

# include <stdio.h>
# include <stdlib.h>
# include <string.h>

int main(){
    
    FILE* file;
    
    char* data = new char[100];

    file = fopen("test.txt", "rt");
    
    int count = 0;
    if(file != NULL){
        char temp[100];
        while(fgets(temp, 100, file) != NULL){
            strtok(temp, "\n"); // fgets()함수가 가져온 "\n"문자를 잘라냄
            strcpy(data, temp);
            printf("[%s]\n", data);
            count++;
        }
    }
    fclose(file);

    printf("count : %d\n", count);


    delete[] data;
    return 0;
}

 

 

'C > ' 카테고리의 다른 글

[59] 구조체와 배열  (0) 2020.07.27
[58] 구조체  (0) 2020.07.27
[57] 연습문제 : 더블 포인터  (0) 2020.07.27
[56] 더블 포인터  (0) 2020.07.27
[55]-A. 가변 배열 컨트롤러  (0) 2020.07.27

댓글