본문 바로가기
정리/C

[c] 파일 입출력

by 멘멘 2023. 8. 27.

fputs와 fgets

#define _ORT_SECURE_NO_WARNINGS
#include <stdio.h>
 
#define MAX 10000
int main(void){

	//파일 입출력
    //파일에 어떤 데이터를 저장
    //파일에 저장된 데이터를 불러오기
    
    //fputs, fgets
    char line[MAX];
    //파일 열기
    FILE * file = fopen("c:\\test1.txt","wb");
  	// r w a
    if(file == NULL){
    	printf("파일열기실패\n");
        return 1;
    }

    //파일 쓰기
    fputs("fput을 이용한 글적기",file);
    
    //파일을 열고 닫지않은 상태에서 프로그램에 문제가 생기면 데이터 손실 발생
    fclose(file);
    
    
   
    
	return 0;
}
#define _ORT_SECURE_NO_WARNINGS
#include <stdio.h>
 
#define MAX 10000
int main(void){

	//파일 입출력
    //파일에 어떤 데이터를 저장
    //파일에 저장된 데이터를 불러오기
    
    //fputs, fgets
    char line[MAX];
    //파일 열기
    FILE * file = fopen("c:\\test1.txt","rb");
  	// r w a
    if(file == NULL){
    	printf("파일열기실패\n");
        return 1;
    }
    
    //파일 읽기
    while(fgets(line,MAX,file) != NULL)
    {
    	printf("%s",line);
    }
    
    //파일을 열고 닫지않은 상태에서 프로그램에 문제가 생기면 데이터 손실 발생
    fclose(file);
    
	return 0;
}

 

fprintf와 fscanf

#define _ORT_SECURE_NO_WARNINGS
#include <stdio.h>
 
#define MAX 10000
int main(void){

	//파일 입출력
    //파일에 어떤 데이터를 저장
    //파일에 저장된 데이터를 불러오기
    
    //fprintf, fscanf
	int num[6] = {0,0,0,0,0,0};    //추첨번호
    int bonus = 0;
    char str1[MAX];
    char str2[MAX];
    
    //파일에 쓰기
    FILE * file = fopen("c:\\test2.txt","wb");
    if(file == NULL){
    	printf("파일열기실패\n");
        return 1;
    }
    
    //로또 추첨 번호 저장
    fprintf(file,"%s %d %d %d %d %d %d\n","추첨번호",1,2,3,4,5,6);
    fprintf(file,"%s %d\n","보너스번호",7);
    
    fclose(file);
    
    
	return 0;
}​
#define _ORT_SECURE_NO_WARNINGS
#include <stdio.h>
 
#define MAX 10000
int main(void){

	//파일 입출력
    //파일에 어떤 데이터를 저장
    //파일에 저장된 데이터를 불러오기
    
    //fprintf, fscanf
	int num[6] = {0,0,0,0,0,0};    //추첨번호
    int bonus = 0;
    char str1[MAX];
    char str2[MAX];
    
    //파일에 쓰기
    FILE * file = fopen("c:\\test2.txt","rb");
    if(file == NULL){
    	printf("파일열기실패\n");
        return 1;
    }
    
    //로또 추첨 번호 저장
    fscanf(file,"%s %d %d %d %d %d %d",str1,
    	&num[0],&num[1],&num[2],&num[3],&num[4],&num[5]);
    printf(file,"%s %d %d %d %d %d %d\n",str1,
    	num[0],num[1],num[2],num[3],num[4],num[5]);
    
    fscanf(file,"%s %d ",str2,&bonus);
    printf(file,"%s %d\n",str2,bonus);
    
    fclose(file);
    
    
	return 0;
}

 

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

[c] 백준 10870  (0) 2023.08.27
[c] 코딩도장 파일입출력 문제  (0) 2023.08.27
[c] 구조체 관련 문제 풀이  (0) 2023.08.27
[C] 구조체  (0) 2023.07.30
[c] 이차원 배열 문제 풀이  (0) 2023.07.23

댓글