Help with function in C?
This is a user defined function that is supposed to load a file and find the string length first and then the following string. Sometimes this function works and other times when it prints the string, the first letter is missing from the string. I'm not sure how to fix it but I think it's with the fgetc function, I don't really know how to use it. Oops. Thanks
- husoskiLv 710 months agoFavorite Answer
The fgetc() function gets one character from the opened file and returns an int result representing either the character code of the character read, or the constant EOF if no character could be read (usually because end-of-file was reached.) Since you don't store the return value, that character is simply discarded.
Sounds a bit like your error, doesn't it?
I'll guess that the file has no space between the length and the first character of the string in some cases. Handling that with fgets() can be a bit tricky. If the return value from fgetc() is not a space, then you need to store it as the first character of the resulting string. Something like:
int ch = fgetc(fileName);
if (ch == ' ')
fscanf(strLength, length+1, fileName);
strLength = (char) ch; // store nonblank as 1st char
fscanf(strLength+1, length, fileName); // then read the rest
I might be tempted to just write a loop, getting *all* the characters of the input string with fgetc. That way I could stop at the end of the line (if encountered before <length> characters were read) without worrying about a trailing '\n' in the return value.
- TasmLv 610 months ago
Try to flush the input buffer fflush(stdin)