#include <stdio.h>
int main()
{
FILE *ptr=NULL; //this is a good practise
char string[34];
ptr = fopen("myfile.txt","r");
fscanf(ptr,"%s",string); //what this do is takes content till space or new line from
and store it to string variable
printf("Content of this file has :%s\n",string);
return 0;
}
Output ↓
Content of this file has :this
#include <stdio.h>
int main()
{
FILE *ptr=NULL;
char string2 [100]="This content was produced by Tutorial64.c";
ptr = fopen("myfile.txt","w");
fprintf(ptr,"%s",string2); //inside the file this string will we inserted
//all the older text got removed and the text stored in string2 was inserted
// ptr = fopen("myfile.txt","a"); // in this mode the text inside string2 will be added he end to the file
return 0;
}
Mode
Description
r
Opens an existing text file for reading
w
Opens a file for writing. If it doesn't exist, then a new file is created. Writing starts from the beginning of the file.
a
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. The program will start appending content to the existing file content.
r+
This mode will open a text file for both reading and writting
w+
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist
a+
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only append to file.
#include <stdio.h>
int main()
{
FILE *ptr = NULL;
ptr = fopen("myfile2.txt","w"); // we have to open this in 'write' mode
fputc('o',ptr);
fclose(ptr);
return 0;
}
#include <stdio.h>
int main()
{
FILE *ptr = NULL;
ptr = fopen("myfile2.txt","w"); // we have to open this in 'write' mode
fputs("Harry is great",ptr);
fclose(ptr);
return 0;
}
#include <stdio.h>
int main()
{
FILE *ptr = NULL;
ptr = fopen("myfile2.txt","r");
char c = fgetc(ptr);
printf("The character I got was : %c\n",c);
fclose(ptr);
return 0;
}
#include <stdio.h>
int main()
{
FILE *ptr = NULL;
ptr = fopen("myfile2.txt","r");
char str[34];
fgets(str, 5, ptr);
printf("The string is : %s\n", str);
fclose(ptr);
return 0;
}