File Creation, Reading From and Writing To File:: CSE115L - Computing Concepts Lab Lab 15
File Creation, Reading From and Writing To File:: CSE115L - Computing Concepts Lab Lab 15
File Creation, Reading From and Writing To File:: CSE115L - Computing Concepts Lab Lab 15
Lab 15
#include<stdio.h>
int main() #include<stdio.h>
{ #include<string.h>
FILE *fp; int main()
fp=fopen("test.txt","r"); {
if(fp != NULL) FILE *fp;
{ fp=fopen("test.txt","r");
printf("File has been opened"); char c;
fclose(fp); while((c=getc(fp))!=EOF)
} putchar(c);
else printf("File not found")
return 0; fclose(fp);
} return 0;
#include<stdio.h> }
#include<string.h>
int main()
{
FILE *fp;
char buffer[30];
strcpy(buffer,"File has been created");
fp=fopen("test.txt","w");
fprintf(fp,buffer);
fclose(fp);
return 0;
}
return 0;
}
Appending a file:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
fp=fopen("append.txt","a");
fprintf(fp,"Append mode");
fclose(fp);
return 0;
}
Problems:
1. Write a program that will read names, ids, dept names, and cgpa of some students from a file and will show
the results. Consider that the name of the file is ‘input.csv’. It is just a text file where each line holds
information of one student. Example format of two lines in the file is as follows:
Read all information from the file, and print them on screen (one student per line). Your program should use
the following structure to hold information of a student
typedef struct
{
char name[50];
int id;
char dept[20];
double cgpa;
} student;
2. Write a function void pintByDept(char *deptName , student allStudents[], int size) that will print the
information of only those students who belong to the department with name pointed to by deptName. The
array allStudent is of length ‘size’ and holds information of all the students.
3. Write a function void saveByDept(char *fileName, char *deptName , student allStudents[], int size) that
will save the information of all students who belong to the department with name pointed to by deptName
into a text file. The name of the file is given as an input parameter, fileName.