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

File Operation

The document provides an overview of file operations in C programming, including file pointers, opening or creating files, and closing files. It explains different modes for file operations such as reading, writing, and appending, along with examples of using fscanf and fprintf for formatted input and output. Additionally, it highlights the difference between write and append modes when handling files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

File Operation

The document provides an overview of file operations in C programming, including file pointers, opening or creating files, and closing files. It explains different modes for file operations such as reading, writing, and appending, along with examples of using fscanf and fprintf for formatted input and output. Additionally, it highlights the difference between write and append modes when handling files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

File operation

File pointer
• FILE *fp;

• * is pointer symbol

• *fp refers to memory of a File


Open or Create File
• *fp = fopen(const char* filename, const char *mode);

• Mode

• ‘r’ : Read in text mode

• ‘w’ : Write in text mode

• ‘a’ : append in text mode

• ‘rb’ : read in binary mode

• Etc …
Close file
• fclose( FILE *fp )
#include<stdio.h>

int main()
{
FILE *fp;
char ch;
fp = fopen(“file.txt", "w");
printf(“Input any texts: ”);
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("file.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

// closing the file pointer


fclose(fp);

return 0;
}
fscanf & fprintf
• Recall : scanf & printf

• fscanf(File pointer, “expression”, arguments …)

• Read from file with specific format

• fprintf(File pointer, “expression”, arguments …)

• Write into file with specific format


#include<stdio.h>

int main()
{
FILE *p,*q;
char name[32];
int age;

p = fopen("file.txt", "w");
printf("Enter Name and Age:");
scanf("%s %d", name, &age);
fprintf(p,"%s %d\n", name, age);
fclose(p);

q = fopen("file.txt", "r");
fscanf(q,"%s %d", name, &age);
printf("%s %d\n", name, age);
fclose(q);
return 0;
}
Write or Append ?
• Both are used to write in a file. In both the modes, new file
is created if it doesn't exists already.

• In write mode, the file is reset, resulting in deletion of any


data already present in the file

• Append mode is used to append or add data to the


existing data of file(if any)

• When open a file in Append mode, the cursor is


positioned at the end of the present data in the file.

You might also like