alberto said:
Keith Thompson escribió:
Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as
char array[50]
But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really
being used in each array ?
If you can define what you mean by "used", the answer will be obvious.
If you can't, there is no answer.
I told on previous massage.
For example, I declare this array:
char arr[50];
And I want to put on that variable what user write on the keyboard
with scanf function (for example, his name). But some times the user
will type 20 characters, and other times will type 40 characters...
The same if the array would be on a file. But how do I know exactly
how many characters typed the user ?
You restricted yourself to a binary file, thus you do not know
how many characters are "used" -- you read 50 and then determine
how many are "used".
If you change your notion to "the file contains zero-terminated
character sequences (vulgo: strings) each of which is no longer
than 50 characters including the terminator", you can read up
to 50 characters, stop earlier when you encounter '\0' and know
how many characters you read ("used") up to that point.
This is curiously close to "the text file contains lines of up
to 50 characters including the newline character". C provides
a function to deal with this case: fgets(). You can use fgets()
also to read from stdin. If you want to be on the safe side,
you can check whether the user really entered/the file really
contained such a character sequence: The last character of the
string's "content" must be a '\n'.
Especially for reading from stdin, you often are restricted to
line-buffered input, so you get the user's input only after
the user hit return.
strlen() can be used to determine the number of characters plus
the '\n'.
If you do not need the '\n', you can overwrite it with '\0'.