File Number Control C Program Example

How to write a C Program to File Number Control in C Programming Language ?

Solution:

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. void main()
  6. {
  7.         FILE *fp, *fc;
  8.         int lineNum;            //stores line number which should be edited.
  9.         int lineCount = 0;              //count number lines in source file.
  10.         int charCount = 0;
  11.         int ch;                         //temporary place to store character of source file(one at a time).
  12.         int edited = 0;         //0=false and 1=true
  13.         int t;                          //temporary place to store input which you want to be replaced with error in text file.
  14.         int *line;
  15.  
  16.         fp = fopen("source.txt", "r+");
  17.         if (fp == NULL)
  18.         {
  19.                 printf("\nError...cannot open/create files");
  20.         }
  21.         line = (int*)malloc(sizeof(int)*(lineCount+1));
  22.         line[0] = 0;
  23.         fseek(fp, 0, SEEK_SET);
  24.         while (true)
  25.         {
  26.                 ch = fgetc(fp);
  27.                 charCount++;
  28.                 if (ch == '\n')  //counts number of lines
  29.                 {
  30.                         lineCount++;
  31.                         line = (int*)realloc(line, sizeof(int)*(lineCount + 1));
  32.                         line[lineCount] = charCount+1;
  33.                 }
  34.                 if (ch == EOF)
  35.                 {
  36.                         lineCount++;
  37.                         line = (int*)realloc(line, sizeof(int)*(lineCount + 1));
  38.                         line[lineCount] = charCount+1;
  39.                         break;
  40.                 }
  41.         }
  42.         for (int i = 0; i <= lineCount; i++)
  43.         {
  44.                 printf("line[%d] byte offset is %d\n", i, line[i]);
  45.         }
  46.         if (fseek(fp, 7, SEEK_SET) != 0)
  47.                 printf("FSEEK ERROR!\n");
  48.         else
  49.                 fprintf(fp, "YYY");
  50.         printf("Number of lines in file: %d", lineCount);
  51.         system("PAUSE");
  52.  
  53. }


Learn More :