0% found this document useful (0 votes)
3 views2 pages

File Handling & Command Line Basics

The document outlines file handling modes in C programming, including read, write, and append modes. It provides example programs for sequential and random access file processing, as well as handling command line arguments to count words. Each section includes code snippets demonstrating the respective functionalities.

Uploaded by

t6726730
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

File Handling & Command Line Basics

The document outlines file handling modes in C programming, including read, write, and append modes. It provides example programs for sequential and random access file processing, as well as handling command line arguments to count words. Each section includes code snippets demonstrating the respective functionalities.

Uploaded by

t6726730
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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]);
}

You might also like