본문 바로가기
학부공부/C_Basic

10. File[C Basic]

by sonpang 2021. 11. 7.
반응형

* fgets exapmle

#include<stdio.h>
int main()
{
	char line[255];
	FILE *file=fopen("example_fputs.txt","r");
	if(file==NULL){
		printf("파일열기 실패\n");
		return 1;
	}
	while((fgets(line,sizeof(line),file))!=NULL)
		printf("%s",line);
	
	fclose(file);
	
	return 0;	
}

 

* fprintf exapmle

#include<stdio.h>
int main()
{
	int num1=20;
	int num2=40;
	
	FILE *file=fopen("example_fprintf.txt","w");
	
	if(file==NULL){
		printf("파일열기 실패\n");
		return 1;
	}
	
	fprintf(file,"%d %d %s \n",num1,num2,"입력되었습니다.");
	fclose(file);
	
	return 0;
	
}

 

* fputs exapmle

#include<stdio.h>

int main()
{
	FILE* file = fopen("example_fputs.txt","wt");
	if(file==NULL){
		printf("파일열기 실패\n");
		return 1;
	}
	fputs("fputs를 이용한 파일 생성 및 입력 \n",file);
	fputs("fputs를 이용한 파일 생성 및 입력 \n",file);
	
	fclose(file);
	
	return 0;
}

 

* fscanf exapmle

#include<stdio.h>
int main()
{
	int num1;
	int num2;
	char str[500];
	
	FILE *file=fopen("example_fprintf.txt","r");
	
	if(file==NULL){
		printf("파일열기 실패\n");
		return 1;
	}
	
	fscanf(file,"%d %d %s \n",&num1,&num2,str);
	printf("%d %d %s\n",num1,num2,str);
	
	fclose(file);
	
	return 0;
	
}

 

* 2 


	file open error출력
	구조체 사용
	입력 후 fprintf(fp,"%s %d %d %s\n",...,...,...,...);
	fclose 후 다시 읽기로 열기 + open error 추가
	fscanf로 해서 다시 불러 들이기 
	구조체 2번 선언 sturct student struct find student[5] 
	FILE *fp1;
	if(fopen(&fp1,"...txt","w")!=NULL){
		printF("error");
		exit(1);//return 0;도 괜찮음. 
	}
	
	


* 4
#include<stdio.h>
#define MAX 5

typedef struct student{
	char name[80];
	int stdnum;
	int kor;
	int math;
	int eng;
	float avg;
}student;
student list[10];

void sort();

int main()
{
	int i;
	FILE *fp1,*fp2;
	if((fopen_s(&fp1,"stdlist.txt","rb"))!=0){//rb or rt 다른 결과 
		printf("File could not be opened\n");
		exit(1);
	}
	/*
	fread(list[0].name,sizeof(char),100,fp1);
	fclose(fp1);
	fp2=fopen("stdlist1.txt","wb");
	fprintf(fp2,list[0].name);
	fclose(fp2);
	*/
	/*
	fread(list[0].name,sizeof(char),9,fp1);
	printf("%-20s",list[0].name);
	fread(&list[0].stdnum,sizeof(int),5,fp1);
	printf("%c",list[0].stdnum);
	*/
	//fread(temp,sizeof(temp),1,fp1);
	//printf("%-20s %-6s %-15s %-5s %-5s %-s\n",list[0].name,list[0].stdnum,list[0].avg,list[0].kor,list[0].math,list[0].eng);
	//char t;
	
	printf("%-20s %-6s %-15s %-5s %-5s %-5s\n","Name","ID","Avg","KOR","MATH","ENG");
	for(i=0;i<MAX;i++){
		/*
		fread(list[i].name,sizeof(char),9,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].stdnum,sizeof(int),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].avg,sizeof(float),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].kor,sizeof(int),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].math,sizeof(int),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].eng,sizeof(int),1,fp1);
		//fread(&t,sizeof(char),1,fp1);
		*/
		
		fread((void*)&list[i],sizeof(student),1,fp1);
		printf("%-20s %-6d %-15f %-5d %-5d %-5d\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
		printf("1");
	}

	sort();
	fopen_s(&fp2,"resultlist.txt","w");
	
	printf("\n%-20s %-6s %-15s %-5s %-5s %-s\n","Name","ID","Avg","KOR","MATH","ENG");
	for(i=0;i<MAX;i++){
		fprintf(fp2,"%s %d %lf %d %d %d",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
		printf("%-20s %-6s %-15s %-5s %-5s %-s\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
	}
	
	fclose(fp1);
	fclose(fp2);
	
	return 0;
}

void sort(){
	int i,j;
	student temp;
	for(i=0;i<MAX;i++){
		for(j=0;j<MAX-1-i;j++){
			if(list[j].avg<list[j+1].avg){
				temp=list[j];
				list[j]=list[j+1];
				list[j+1]=temp;
			}
		}
	}
}

fread(list[i].name,sizeof(char),9,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].stdnum,sizeof(int),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].avg,sizeof(float),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].kor,sizeof(int),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].math,sizeof(int),1,fp1);
		fread(&t,sizeof(char),1,fp1);
		fread(&list[i].eng,sizeof(int),1,fp1);
와 
fread(&list[i],sizeof(student),1,fp1);
는 동일 결과

 

10.1.

Write a program that takes two text files: toRead.txt and toWrite.txt

Copy the contents of the first text file (toRead.txt) into the second text file (toWrite.txt), but delete empty line

Put your toRead.txt file at your project repository

#include<stdio.h>
int main()
{
	char readfile[20],writefile[20];
	char text[1000];
	
	printf("Enter the name of file to read : ");
	scanf("%s",readfile);
	FILE *fp1;
	
	if((fp1=fopen(readfile,"r"))==NULL){
		printf("File %s read error\n",readfile);
		exit(1);	
	}

	printf("Enter the name of file to write : ");
	scanf("%s",writefile);

	FILE *fp2=fopen(writefile,"w");
	
	while(fgets(text,sizeof(text),fp1)!=NULL){
		if(*text!='\n')//*s!="\n"?
			fputs(text, fp2);
	}
	
	fclose(fp1);
	fclose(fp2);
	
	printf("Copy txt complete!\n");
	
	return 0;
}

 

10.2.

Write a program that takes inputs 5 students’ information (that is, name, student number, grade, major), and writes them into “student_file.txt”

After that, the program takes a student number, and searches for the corresponding major in the “student_file.txt”, and displays it on the screen

#include<stdio.h>
typedef struct student{
	char name[20];
	int id;
	int grade;
	char major[20];
}student;

int main()
{
	int i, search;
	student data;
	student list[5];
	
	FILE *fp1=fopen("student_file.txt","w");
	
	for(i=0;i<5;i++){
		printf("Name Student_number Grade Major : ");
		scanf("%s %d %d %s",data.name,&data.id,&data.grade,data.major);
		fprintf(fp1,"%s %d %d %s\n",data.name,data.id,data.grade,data.major);
	}
	fclose(fp1);
	
	FILE *fp2=fopen("student_file.txt","r");
	if(fp1==0){
		printf(" Error about File occurred\n");
		exit(1);
	}
	
	printf("Insert the student number to find : ");
	scanf("%d",&search);
	
	for(i=0;i<5;i++){
		fscanf(fp2,"%s %d %d %s",list[i].name,&list[i].id,&list[i].grade,list[i].major);
		if(list[i].id==search)
			printf("The major of student with ID %d is %s\n",search,list[i].major);	
	}
	fclose(fp2);
	
	return 0;
}

 

10.3.

Write a program that reads (2x3)-matrix from the “input1.txt” and “input2.txt”, and writes the summation of given two matrices in “result.txt”

#include<stdio.h>
int main()
{
	int i,j;
	int input1[2][3], input2[2][3], result[2][3];
	FILE *fp1, *fp2, *fp3;
	
	
	if((fopen_s(&fp1,"input1.txt","rt"))!=0){
		printf("File could not be opened\n");
		exit(1);
	}
	printf("input1 matrix : \n");
	for(i=0;i<2;i++){
		for(j=0;j<3;j++){
			fscanf(fp1,"%d",&input1[i][j]);
			printf("%d\t",input1[i][j]);
		}
		printf("\n");
	}
	
	if((fopen_s(&fp2,"input2.txt","rt"))!=0){
		printf("File could not be opened\n");
		exit(1);
	}
	
	printf("\ninput2 matrix : \n");	
	for(i=0;i<2;i++){
		for(j=0;j<3;j++){
			fscanf(fp2,"%d",&input2[i][j]);
			printf("%d\t",input2[i][j]);
		}
		printf("\n");
	}
	
	fp3=fopen("result.txt","w");
	printf("\nresult matrix : \n");	
	for(i=0;i<2;i++){
		for(j=0;j<3;j++){
			result[i][j]=input1[i][j]+input2[i][j];
			fprintf(fp3,"%d\t",result[i][j]);
			printf("%d\t",result[i][j]);
		}
		fprintf(fp3,"\n");
		printf("\n");
	}
	
	fclose(fp1);
	fclose(fp2);
	fclose(fp3);
	
	return 0;	
}

 

10.4.

Write a program that reads the student list from the file “stdlist.txt” and prints the list of students according to students’ average grade.

Then, write the student list to the file “resultlist.txt”

Use “fread” function to read the student list and “fprintf” function to write.

Use student struct

Struct student {
     char name[80];
     int stdnum;
     int kor;
     int math;
     int eng;     
     float avg;
};
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 5

typedef struct student{
	char name[80];
	int stdnum;
	float avg;
	int kor;
	int math;
	int eng;
}student;
student list[MAX];

void sort();

int main()
{
	int i;
	FILE *fp1,*fp2;
	
	if((fopen_s(&fp1,"stdlist.txt","rb"))!=0){//rb or rt 다른 결과 
		printf("File could not be opened\n");
		exit(1);
	}
	
	printf("%-20s %-6s %-15s %-5s %-5s %-5s\n","Name","ID","Avg","KOR","MATH","ENG");
	
	char line[1000],*temp;
	fread(line,sizeof(char),1000,fp1);
	temp=strtok(line," \n\t");
	for (i = 0;i < MAX;i++) {
		strcpy(list[i].name,temp);
		temp = strtok(NULL, " \n\t");
		list[i].stdnum=atoi(temp);
		temp = strtok(NULL, " \n\t");
		list[i].avg=atof(temp);
		temp = strtok(NULL, " \n\t");
		list[i].kor=atoi(temp);
		temp = strtok(NULL, " \n\t");
		list[i].math=atoi(temp);
		temp = strtok(NULL, " \n\t");
		list[i].eng=atoi(temp);
		temp = strtok(NULL, " \n\t");
		printf("%-20s %-6d %-15f %-5d %-5d %-5d\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
	}
	/*
	for(i=0;i<MAX;i++){
		fread(&list[i],sizeof(student),1,fp1);
			
		//fscanf(fp1,"%20s %d %f %d %d %d",list[i].name,&list[i].stdnum,&list[i].avg,&list[i].kor,&list[i].math,&list[i].eng);
		
		fread(list[i].name,sizeof(char),9,fp1);
		fread(&list[i].stdnum,sizeof(int),1,fp1);
		fread(&list[i].avg,sizeof(float),1,fp1);
		fread(&list[i].kor,sizeof(int),1,fp1);
		fread(&list[i].math,sizeof(int),1,fp1);
		fread(&list[i].eng,sizeof(int),1,fp1);
		printf("%-20s %-6d %-15f %-5d %-5d %-5d\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
	}
	*/	
	/*
	while(fread(&list[i],sizeof(student),1,fp1))
		printf("%-20s %-6d %-15f %-5d %-5d %-5d\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
	*/
	sort();
	fopen_s(&fp2,"resultlist.txt","w");

	printf("\n%-20s %-6s %-15s %-5s %-5s %-5s\n","Name","ID","Avg","KOR","MATH","ENG");
	for(i=0;i<MAX;i++){
		fprintf(fp2,"%s %d %f %d %d %d\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
		printf("%-20s %-6d %-15f %-5d %-5d %-5d\n",list[i].name,list[i].stdnum,list[i].avg,list[i].kor,list[i].math,list[i].eng);
	}
	
	fclose(fp1);
	fclose(fp2);
	
	return 0;
}

void sort(){
	int i, j;
	student temp;
	
	for(i = 0;i < MAX;i++){
		for(j = 0;j < MAX - 1 - i;j++){
			if(list[j].avg < list[j+1].avg){
				temp = list[j];
				list[j] = list[j+1];
				list[j+1] = temp;
			}
		}
	}
}

 

* fread example

#include <stdio.h>
 
#define MAX_NAME_LEN    20
typedef struct {
    char name[MAX_NAME_LEN + 1];
    int age;
}Member;
 
#define MAX_MEMBERS 10
int main(void)
{
    FILE * fp;
    int i;
    Member members[MAX_MEMBERS] =
    {
        { "홍길동",20 },{ "강감찬",15 },{ "을지문덕",22 },{ "이순신",19 },{ "김구",30 },
        { "안중근",30 },{ "박찬호",35 },{ "김연아",17 },{ "아이유",20 },{ "주니엘",20 }
    };
    Member members2[MAX_MEMBERS];
 
    //쓰기 모드로 파일 열기
    fopen_s(&fp, "data.txt", "wb");
    if (fp == NULL)
    {
        perror("error fopen");
        return;
    }
    //출력 파일 스트림에 members 배열의 내용 출력
    if (fwrite(members, sizeof(Member), MAX_MEMBERS, fp) != MAX_MEMBERS)
    {
        printf("출력 오류\n");
        return;
    }
    fclose(fp);//출력 파일 스트림 닫기
 
               //읽기 모드로 파일 열기
    fopen_s(&fp, "data.txt", "rb");
    if (fp == NULL)
    {
        perror("error fopen");
        return;
    }
 
    //파일에서 members2 배열로 데이터 읽기
    fread(members2, sizeof(Member), MAX_MEMBERS, fp);
    //읽어온 데이터 출력
    printf("%-10s %-10s\n", "이름", "나이");
    for (i = 0; i<MAX_MEMBERS; i++)
    {
        printf("%-10s %-10d\n", members2[i].name, members2[i].age);
    }
    fclose(fp); //입력 파일 스트림 닫기
    return 0;
}

 

* stdlistmaking

#include<stdio.h>
typedef struct student{
	char name[20];
	int stdnum;
	float avg;
	int kor;
	int math;
	int eng;
}student;
student list;

int main()
{
	FILE *fp1=fopen("stdlist2.txt","w");
	int i;
	for(i=0;i<5;i++){
		scanf("%s %d %f %d %d %d",list.name,&list.stdnum,&list.avg,&list.kor,&list.math,&list.eng);
		fwrite(&list,sizeof(student),1,fp1);
	}
	
	fclose(fp1);
	return 0;
}
/*
#include<stdio.h>
typedef struct student{
	char name[20];
	int stdnum;
	float avg;
	int kor;
	int math;
	int eng;
}student;
student list;
int main()
{
	FILE *fp=fopen("stdlist1.bin","wb");
	int i;
	char line[80];
	
	fgets(line,"80",stdin);
	while(!feof(stdin)){
		sscanf_s(line,"%s %d %f %d %d %d",list.name,20,&list.stdnum,&list.avg,&list.kor,&list.math,&list.eng);
		fgets(line,80,stdin);
	}
	
	fclose(fp);
	
	return 0;
}

#include<stdio.h>
typedef struct student{
	char name[20];
	int stdnum;
	float avg;
	int kor;
	int math;
	int eng;
}student;
student list[]={
{"Student1",1936,18.000000,39,10,5},
{"Student2",1961,58.666668,16,97,63},
{"Student3"	1965,48.666668,76,25,45},
{"Student4"	1596,44.666668,78,41,15},
{"Student5"	1250,56.000000,62,20,86}
};
int main()
{
	FILE *fp=fopen("stdlist1.bin","wb");
	int i;
	for(i=0;i<5;i++){
		
	}
	
	fclose(fp);
	
	return 0;
}
*/

 

* stdlistmaking2

#include<stdio.h>
typedef struct student{
	char name[20];
	int stdnum;
	float avg;
	int kor;
	int math;
	int eng;
}student;
student list;

int main()
{
	FILE *fp1=fopen("stdlist2.txt","w");
	int i;
	for(i=0;i<5;i++){
		scanf("%s %d %f %d %d %d",list.name,&list.stdnum,&list.avg,&list.kor,&list.math,&list.eng);
		fwrite(&list,sizeof(student),1,fp1);
	}
	
	fclose(fp1);
	return 0;
}
반응형

'학부공부 > C_Basic' 카테고리의 다른 글

1. Project_KU Mobile Phone Bill Calculator[C Basic]  (0) 2021.11.07
1. Quiz[C Basic]  (0) 2021.11.07
9. Struct[C Basic]  (0) 2021.11.07
8. Bit operator[C Basic]  (0) 2021.11.07
7. String[C Basic]  (0) 2021.11.07

댓글