Brand new to C here. The program is supposed to read in a file of fragments on a single line, separated by a “#” before and after them. For example #fragment1##fragment2##fragment3#
The two errors I want to check for are that a fragment is not over 1000 characters, and that the file follows the correct format of “#” on either side of fragments. I don’t really get how fscanf syntax works but I think the following would check for the errors:
char buffer[MAX_FRAG_LEN+1];
if (fscanf(fp, "#%1000[^#]#", buffer) == 1) {
return strdup(buffer);
} else {
fprintf(stderr, "Error! Incorrect format.\n");
}
However, I want to separate the errors so I can specifically deliver a message of which of the two it was. How can I make the checks individually? Much appreciated!
To make your technique work, you should manually check if the next character after the buffer is a
'#'afterfscanfreturns. This allows you to distinguish a too long string error from a missing"##"error.However, using
fscanffor parsing is generally tricky. If the input is in a totally unexpected format, it can be difficult to recover from them correctly. So, it is usually easier to handle errors by reading in the entire line in a single buffer, and then parse that line instead, as suggested by Duck.