Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define SIZE 100
  5.  
  6. int main() {
  7.  
  8.     // Pointer to the memory where the FILE structure is stored
  9.     FILE *fp;
  10.  
  11.     // Opening a file for writing
  12.     fp = fopen("example.txt", "w");
  13.     if (fp == NULL) {
  14.         printf("Error while opening the file");
  15.         return 0;
  16.     }
  17.     // Writing to a file with appropriate format
  18.     fprintf(fp, "%s\n", "Example:");
  19.     // Writing to a file character by character
  20.     char text[80] = "Structured Programming Exam Exercises";
  21.     char *p = text;
  22.     while (*p) {
  23.         int result = fputc((int) *p, fp);
  24.         if (result == EOF) {
  25.             printf("Error while writing to file\n");
  26.         }
  27.         p++;
  28.     }
  29.     // Closing a file
  30.     fclose(fp);
  31.  
  32.     // Opening a file for reading
  33.     fp = fopen("example.txt", "r");
  34.     if (fp == NULL) {
  35.         printf("Error while opening the file");
  36.         return 0;
  37.     }
  38.     // Reading a file character by character
  39.     int ch;
  40.     while (1) {
  41.         ch = fgetc(fp);
  42.         if (ch == EOF) {
  43.             break;
  44.         }
  45.         printf("%c", (char) ch);
  46.     }
  47.  
  48.     // Reading a file word by word
  49.     char word[SIZE];
  50.     while (fscanf(fp, "%s", word) != NULL) {
  51.         // Do something with the word
  52.     }
  53.  
  54.     // Reading a file row by row
  55.     char row[SIZE;
  56.     while (fgets(row, SIZE, fp)) {
  57.         // Do something with the row
  58.     }
  59.  
  60.     // Closing a file
  61.     fclose(fp);
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement