I want to process a file line by line in c, all lines in the file must be of length 100 characters if the line exeed this or the line is empty i want to print the number of the line in error and continu to the next line.
i’m using this but it doesn’t work:
int maxLineLen = 101; // 100 + 1 for the '\n' end of line
char myBuffer[101];
FILE *myFile;
myFile = fopen("dataFile.txt", "r");
while (fgets(myBuffer, maxLineLen, myFile) != NULL) {
// I can't figure out how to detect and print empty or error lines
}
Thank’s fro the help.
Edit : I added this sample of my file :
// Empty line : Wrong line
FirstName-Paolo-LastName-Roberto-Age-23-Address-45,abcdefghijklmnopqrst-CustomerId-xxxxxxxxxxxxxxxx // Correct line
FirstName-Juliana-LastName-Mutti-Age-35-Address-28,abcdefghijklmnopqrst-CustomerId-xxxxxxxxxxxxxxxABCDEFGHIJx // Exeed the length : Wrong line
FirstName-David-LastName-Lazardi-Age-59-Address-101,abcdefghijklmnopqrst-CustomerId // Short length : Wrong line
When i run my program i should get :
Line 1 : ERROR
Line 3 : ERROR
Line 4 : ERROR
Since you need to detect both underlength and overlength lines reliably, and resynchronize you input after either, it is probably easiest to write a function that uses
getc()to read the data.Your standard function options include:
fgets()— won’t read too much data, but you’d have to determine whether it got a newline (which would be included in the input) and deal with resynchronization when reading an over-length line (not very difficult).fread()— will read exactly the right length, and would be a good choice if you think overlength and underlength lines will be vanishingly rare occurrences. Resynchronization after an error is anything but trivial, especially if you get adjacent erroneous lines.getline()— from POSIX 2008. Allocates sufficient memory for the length of line it reads, which is a little wasteful if you’re simply going to discard over-length lines.Because they aren’t suitable, you end up writing your own.
Now tested code. (The fix was needed in the first
ifas diagnosed by Dave. The trouble was I originally wrote the inverse condition (if ((c = getc(fp)) != EOF && c != '\n')), then got distracted after I inverted the logic, leading to an ‘incomplete inversion’ of the condition.)The key parts of this are the two while loops.
The first while loop reads to the end of the line, storing the data and counting characters — the normal operation. If the line is the right length, the loop will be broken when the newline is read.
Note theIf the line is short, the<=condition; if you consider the loop whenlinelen == 1, you will see that<=is correct here even though<is more usual.countwill indicate that.The second while loop deals with overlong lines, reading to the end of the line and discarding the results. It uses
xinstead ofcbecausecis needed in the return statement.Test data and output