Unit 4 – File Handling & Command Line Arguments (Answers)
1. File Modes:
r - read
w - write
a - append
r+ - read/write
w+ - write/read
a+ - append/read
rb - read binary
wb - write binary
ab - append binary
2. Program using a+ mode:
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]","a+");
int roll, mark;
char name[50];
printf("Enter Roll:");
scanf("%d",&roll);
printf("Enter Name:");
scanf("%s",name);
printf("Enter Mark:");
scanf("%d",&mark);
fprintf(fp,"%d %s %d
",roll,name,mark);
fclose(fp);
}
3. Sequential File Processing:
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]","w");
int n;
char name[50];
printf("Enter number:");
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%s",name);
fprintf(fp,"%s
",name);
}
fclose(fp);
fp = fopen("[Link]","r");
while(fscanf(fp,"%s",name)!=EOF)
printf("%s
",name);
fclose(fp);
}
Random Access File Processing:
#include <stdio.h>
struct Student { int roll; char name[30]; int mark; };
int main() {
FILE *fp = fopen("[Link]","r+b");
struct Student s;
int searchRoll,newMark;
scanf("%d",&searchRoll);
while(fread(&s,sizeof(s),1,fp)){
if([Link]==searchRoll){
scanf("%d",&newMark);
[Link] = newMark;
fseek(fp,-sizeof(s),SEEK_CUR);
fwrite(&s,sizeof(s),1,fp);
}
}
fclose(fp);
}
4. Command Line Arguments – Count Words:
#include <stdio.h>
int main(int argc,char *argv[]){
printf("Words: %d
",argc-1);
for(int i=1;i<argc;i++)
printf("%s
",argv[i]);
}