Reputation: 3
I was writing a programm which must read a word, which is separated from others by a ' '
or \n
, from a file (I decided to use 'read'
system function for it) and faced up an issue with it.
In particular, as it is written in manual, 'read'
must return 0
when there is nothing else to read (EOF
is reached), but in my case it returns \n
(I checked the ASCII
code of returned symbol and it's 10
which is of \n
and checked my program a number of times and it always returns the same). Here's the code
char *read_word_from_file(int fd, int *flag)
{
int i = 0;
char ch, *buf = NULL;
if (!read(fd, &ch, 1)) { //file is empty
*flag = 1;
return NULL;
}
while (ch != ' ' && ch != '\n') {
if (!(buf = (char *) realloc(buf, i + 1))) goto mem_err;
buf[i++] = ch;
if (!(read(fd, &ch, 1))) {
*flag = 1;
break;
}
}
buf[i] = '\0';
return buf;
mem_err:
perror("realloc");
exit(1);
}
(flag
variable is used to indicate the EOF
for the outer function, which calls this one) So, my question is "is such behavior is normal, or I made a mistake somewhere?"
P.S. - Off-topic question, how do you make a part of text(a single word) shadowed like a code samples?
Upvotes: 0
Views: 83
Reputation: 19405
gedit simply doesn't show newlines in files. Why is there a newline in your file? Depends on how you created that file. If you used for example puts("M");
then you should understand that puts() adds a newline. If you created it with an editor, you should understand that editors usually write complete lines ending in a newline.
– Jens
Upvotes: 1