yo_mismo <qw*@rty.com> wrote:
I'm trying to read the first line of a file this way:
char *line="";
char info;
...
...
...
new_line=0;
while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){
if (strcmp(&info, "\n") != 0){
strcat(line,info);
}
else{
new_line=1;
}
}
But i can't find the end of the line and this code goes until the end of the
file instead the end of the line.
Your first problem is that this is at least partly off-topic in clc,
there's no standard C function called read(). Please ask in a group
that's concerned with your operating system. You probably would have
less problems if you would use a (standard C) function like fget()
instead. Just make sure that 'info' is an int or you won't be able
to detect the EOF (and, of course, use a stream pointer (FILE*)
instead of a file descriptor).
The other problem is that i get a segmentation fault in strcat(line, info),
i've declared the variables like this:
That's no surprise. 'line' is a char pointer, pointing to a string
that contains just the '\0' character. Now, the initialization makes
it point to a "literal string", i.e. a string that can't be changed.
Moreover, even if you would be allowed to change that string, you
still would have only room for a single char (and that's already
taken by the end-of-string delimiter '\0'), so you can't put any-
thing more into it. What you need is either a large enough array of
characters or a dynamically allocated buffer.
Second, you can't use strcmp() and strcat() here. They both work on
strings, i.e. arrays of chars that have a '\0' at the end of the
text they are supposed to contain. But 'info' is just a single char,
not an array of chars. If you haven't silenced your compiler it
should at least complain loudly about your call of strcat() since
the second argument isn't a char pointer but a char (it won't for
strcmp() because you pass it the address of the 'info' char, so it
can't determine that what you pass it won't be a string).
Regards, Jens
--
\ Jens Thoms Toerring ___
Je***********@physik.fu-berlin.de
\__________________________
http://www.toerring.de