Stormboy
Newbie
Hi,
I just made this little program in C because I started learning it a few days. This program opens a file (it opens the file in read-only mode) eg: .txt, .c, .cpp, .py, etc and returns the total number of lines in the file. It also has error handling, so instead of crashing when the input file is not found, it shows an error message and waits for the user to press a key.
Here is a screenshot:
Here is the code (you can compile it with a C compiler like gcc, MSVC, etc):
WARNING: Large code (70 lines)
Hope you like it.
I just made this little program in C because I started learning it a few days. This program opens a file (it opens the file in read-only mode) eg: .txt, .c, .cpp, .py, etc and returns the total number of lines in the file. It also has error handling, so instead of crashing when the input file is not found, it shows an error message and waits for the user to press a key.
Here is a screenshot:
Here is the code (you can compile it with a C compiler like gcc, MSVC, etc):
WARNING: Large code (70 lines)
Code:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define BUFFERSIZE 10240
int findTotalLines(FILE *filename);
int main()
{
//Variable declarations
char userFile[30];
int total_lines;
int error_num;
int j;
FILE *foofile;
//Get the file name from user
printf("Enter a file name (max 25 chars in length): ");
fgets(userFile, 30, stdin);
//Remove newline from the input
for(j = 0; j < strlen(userFile); j++)
{
if(userFile[j] == '\n')
{
userFile[j] = '\0';
break;
}
}
//Process the file and get line number(s)
foofile = fopen(userFile, "r");
//Error handling if file not found
if(foofile == NULL)
{
error_num = errno;
printf("\nError(%d): %s\n", error_num, strerror(error_num));
printf("\nPress ANY key to exit...");
getch();
return 0;
}
total_lines = findTotalLines(foofile);
fclose(foofile);
//Show the output
printf("\nNo. of lines in %s: %d\n", userFile,total_lines);
printf("\nPress ANY key to exit.");
getch();
return 0;
}
//Function to find the line numbers
int findTotalLines(FILE *filename)
{
char readStrings[BUFFERSIZE];
int lines = 0;
int i;
//Keep on looping until we reach the end of file and fgets returns NULL
while(fgets(readStrings, BUFFERSIZE, filename) != NULL)
{
for(i = 0; i < strlen(readStrings); i++)
{
if(readStrings[i] == '\n')
{
lines += 1;
}
}
}
return lines+1;
}
Hope you like it.