Cse115 Lab Manual 19 File
Cse115 Lab Manual 19 File
1. Opening & closing a text file: 2. Writing user inputs to a text file:
#include<stdio.h> #include<stdio.h>
void main() #include<string.h>
{ void main()
FILE *fp; {
fp=fopen("test.txt","r"); FILE *fp;
if(fp != NULL) char buffer[30];
{ fp=fopen("test.txt","w");
printf("File opened"); if(fp == NULL)
fclose(fp); {
} printf("Error"); return;
else printf("Error"); }
} printf("Enter text to write to
file (hit only enter to stop):\n");
while(1){
gets(buffer);
if(strcmp(buffer,"")==0) break;
fprintf(fp,buffer);
}
fclose(fp);
}
3. Reading from a text file: 4. Appending to a text file:
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main()
{ int main()
FILE *fp; {
fp=fopen("test.txt","r"); FILE *fp;
char c; fp=fopen("test.txt","a");
while((c=getc(fp))!=EOF) fprintf(fp,"Added stuffs");
putchar(c); fclose(fp);
return 0;
fclose(fp); }
}
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fpointer;
fpointer = fopen("input.txt", "w");
fprintf(fpointer, "Bob\n30\n20000\n");
fprintf(fpointer, "Amanda\n20\n10000\n");
fclose(fpointer);
}
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fpointer;
char name[100];
int age;
float salary;
void main ()
{
FILE *file;
int i;
for(i=0; ; i++){
printf ("Firstname (just hit enter to stop):");
gets(cust[i].fname);
if(strcmp(cust[i].fname,"")==0) break;
fflush(stdin);
printf ("Lastname:");
gets(cust[i].lname);
fflush(stdin);
printf ("Acct No:");
scanf("%d", &cust[i]. acct_num);
fflush(stdin);
printf ("Acct Balance:");
scanf("%f", &cust[i].acct_balance);
fflush(stdin);
}
num = i;
fwrite(cust, sizeof(struct customer), i, file);
fclose(file);
}
8. Reading structures from files:
#include <stdio.h>
#include <stdlib.h>
struct customer
{
char fname[20],lname[20];
int acct_num;
float acct_balance;
}cust[100];
void main ()
{
FILE *file;
int i;
num = fread (cust, sizeof(struct customer), 100, file);
for(i=0; i<num; i++)
{
printf ("Name: %s %s, Acct# %d, Balance=%0.2f\n",
cust[i].fname, cust[i].lname, cust[i].acct_num,
cust[i].acct_balance);
}
fclose(file);
}
Exercise:
1. Incorporate reading & writing to/from file in your project so that each time user starts the program, it
doesn’t read from user, instead it reads from a certain file and then show those to the user. Also, just
before the program finishes, the program should store your array of structures in a file.
Hint: combine the ideas in example 7 and 8 above to read & write to/from a file.
2. Write a main menu, which will offer the user to enter records, show records, or to save&exit.