Code works perfectly fine with any compiler on Windows, but not on Linux. On Linux it returns more than double the rows and a negative number of columns. Win8.1 x86_64, Linux 16.04 64bit. I have GCC v5.3 on Windows (MINGW), but GCC v5.4.0 on Linux.
#include <stdio.h>
// count Lines of a file
size_t countLinesOfFile(char *fileName)
{
FILE *fp = fopen(fileName, "r");
char ch;
size_t lines = 0;
do {
ch = fgetc(fp);
if(ch == '\n' || ch == '\r')
lines++;
} while (ch != EOF);
//while (!feof(fp))
// if last line doesn't end with a new line character! augment No of lines
if(ch != '\n' || ch != '\r')
lines++;
fclose(fp);
return lines;
}
// assuming that the file has equal number of columns for all its lines
// (or just 1 line)
size_t countColumnsOfFile(char *fileName)
{
FILE *fp = fopen(fileName, "r");
char ch;
size_t columns = 0;
while ((ch != '\n' || ch != '\r') && ch != EOF) { // we only want to count one line so which ever comes first
ch = fgetc(fp);
columns++;
}
columns--;
//feof(fp) = found end of file, returns non zero(true) if found
fclose(fp);
return columns;
}