How to write a C Program to File Number Control in C Programming Language ?
Solution:
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <stdlib.h>
- void main()
- {
- FILE *fp, *fc;
- int lineNum; //stores line number which should be edited.
- int lineCount = 0; //count number lines in source file.
- int charCount = 0;
- int ch; //temporary place to store character of source file(one at a time).
- int edited = 0; //0=false and 1=true
- int t; //temporary place to store input which you want to be replaced with error in text file.
- int *line;
- fp = fopen("source.txt", "r+");
- if (fp == NULL)
- {
- printf("\nError...cannot open/create files");
- }
- line = (int*)malloc(sizeof(int)*(lineCount+1));
- line[0] = 0;
- fseek(fp, 0, SEEK_SET);
- while (true)
- {
- ch = fgetc(fp);
- charCount++;
- if (ch == '\n') //counts number of lines
- {
- lineCount++;
- line = (int*)realloc(line, sizeof(int)*(lineCount + 1));
- line[lineCount] = charCount+1;
- }
- if (ch == EOF)
- {
- lineCount++;
- line = (int*)realloc(line, sizeof(int)*(lineCount + 1));
- line[lineCount] = charCount+1;
- break;
- }
- }
- for (int i = 0; i <= lineCount; i++)
- {
- printf("line[%d] byte offset is %d\n", i, line[i]);
- }
- if (fseek(fp, 7, SEEK_SET) != 0)
- printf("FSEEK ERROR!\n");
- else
- fprintf(fp, "YYY");
- printf("Number of lines in file: %d", lineCount);
- system("PAUSE");
- }