1#include<stdio.h>
2int main(){
3 FILE *out=fopen("name_of_file.txt","w");
4 fputs("Hello File",out);
5 fclose(out);
6 return 0;
7}
1#include <stdio.h>
2#include <stdlib.h>
3
4int main() {
5 char sentence[1000];
6
7 // creating file pointer to work with files
8 FILE *fptr;
9
10 // opening file in writing mode
11 fptr = fopen("program.txt", "w");
12
13 // exiting program
14 if (fptr == NULL) {
15 printf("Error!");
16 exit(1);
17 }
18 printf("Enter a sentence:\n");
19 fgets(sentence, sizeof(sentence), stdin);
20 fprintf(fptr, "%s", sentence);
21 fclose(fptr);
22 return 0;
23}
24
1/*Program to read from file using getc() function*/
2#include <stdio.h>
3int main() {
4 FILE *fp;
5 char ch;
6 /*Open file in read mode*/
7 fp= fopen ('example.txt', 'r');
8 while( (ch = getc(fp)) != EOF) {
9 /*getc() function reads a character and its value is stored in variable 'ch' until EOF is encountered*/
10 printf('%ch', ch);
11 }
12 fclose(fp);
13 return 0;
14}
1 [...]
2 printf("Enter name: \n");
3 if (fgets(name, sizeof name, stdin)) {
4 fputs(name,fileptr);
5 fclose(fileptr);
6 printf("File write was successful\n");
7 } else {
8 printf("Read error.\n");
9 }
10