Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- int main () {
- FILE *fp;
- unsigned int fileSize;
- char *buffer;
- size_t result;
- unsigned int numOfLines = 0;
- char *cur, *end;
- bool befNotEmpty = false;
- //#define STRSIZE 1024
- //static char str[STRSIZE];
- fp = fopen("file.txt" , "r");
- if(fp == NULL)
- {
- printf("Error opening file");
- return -1;
- }
- /*
- if(fseek(fp, 0L, SEEK_SET) != 0 )
- {
- //Handle error
- }
- */
- //obtain file size:
- fseek(fp, 0 , SEEK_END);
- fileSize = ftell(fp);
- fseek(fp, 0, SEEK_SET);
- buffer = malloc(fileSize);
- if (buffer == NULL)
- {
- fclose(fp);
- printf("Memory error\n");
- return -1;
- }
- result = fread(buffer, 1, fileSize, fp);
- if(result != fileSize)
- {
- free(buffer);
- fclose(fp);
- printf("Reading error\n");
- return -1;
- }
- /*
- OD
- OA
- ODOA
- 0A0D
- 0A0A0A0A..., 0D0D0D0D...
- can be badly formatted
- can end without line terminator
- */
- end = buffer + fileSize;
- cur = buffer;
- while(1)
- {
- if(!(end-cur))
- {
- if(befNotEmpty) numOfLines++;
- break;
- }
- if(*cur == '\r')
- {
- befNotEmpty = false;
- numOfLines++;
- if (++cur < end)
- {
- if(*cur == '\n')
- {
- cur++;
- continue;
- }
- else if(*cur == '\r')
- {
- numOfLines++;
- cur++;
- continue;
- }
- }
- else break;
- }
- else if(*cur == '\n')
- {
- befNotEmpty = false;
- numOfLines++;
- if (++cur < end)
- {
- if(*cur == '\r')
- {
- cur++;
- continue;
- }
- else if(*cur == '\n')
- {
- numOfLines++;
- cur++;
- continue;
- }
- }
- else break;
- }
- else befNotEmpty = true;
- cur++;
- }
- printf("Number of lines: %d\n", numOfLines);
- free(buffer);
- fclose(fp);
- printf("Bye bye.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment