C언어

파일 입출력

joo_coding 2025. 4. 3. 16:41
#include <stdio.h>

int main()
{
    FILE * fp=fopen("./data2.txt","wt"); //출력스트림
    if (fp==NULL)
    {
        puts("오픈 실패");
        return -1;
    }
    fputc('Abc', fp); // putc는 문자열이 아니라 문자를 받는거라서, 여러개를 써도 맨끝에 하나만 저장됨
    fclose(fp); // 파일을 닫아주지않으면 전송한 데이터는 출력버퍼에만 남아있어서, 닫아준 다음 반환하지 않으면 전송되지 않는다.
    return 0;
}

 

fopen ( 파일이름, 스트림종류 )

스트림종류 1.입력 rt / 2.출력 wt (t는 텍스트모드 라는 뜻)

 

#include <stdio.h>

int main()
{
    // 파일출력
    char str[30];
    int ch;
    FILE *fp = fopen("simple.txt", "rt");
    if (fp==NULL)
    {
        puts("오픈 실패");
        return -1;
    }
    ch = fgetc(fp);
    printf("%c\n", ch); //개행으로 열 구분

    fgets(str, sizeof(str), fp);
    printf("%s\n", str);

    fclose(fp);
    return 0;
}

 

파일에서는 개행을 기준으로 문자열을 구분한다

 

#include <stdio.h>

typedef struct fren
{
    char name[10];
    char sex;
    int age;
} Friend;


int main()
{
    FILE *fp;
    Friend myfren1;
    
    fp = fopen("friend.bin", "wb");
    printf("이름, 성별, 나이 순 입력: ");
    scanf("%s %c %d", myfren1.name, &(myfren1.sex), &(myfren1.age));
    fwrite((void*)&myfren1, sizeof(myfren1), 1, fp);
    fclose(fp);

    fp = fopen("friend.bin", "rb");
    fread((void*)&myfren1, sizeof(myfren1), 1, fp);
    printf("%s %c %d \n", myfren1.name, myfren1.sex, myfren1.age);
    fclose(fp);
    return 0;
}

구조체를 파일에 넘기는 방법

구조체 변수를 하나의 바이너리 데이터로 인식