Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fgets agony! 1

Status
Not open for further replies.

tdkratboy

Programmer
Feb 23, 2005
2
US
Hello all, was wondering if there was anyone who could possiblly explain to me an alternative method of reading a file stream? I am using 'fgets' to read a phrase from a text file, the MSDN specifies that it reads until a \n, a null, or the amount of characters specified is encountered. However All of my strings are coming up with a [] square looking character at the end of the string when I output them. Can anyone give me any insight into what is actually going on? However if I shorten the specified characters i.e. fgets(string, 10, stream) and the stream is 20 characters long, the square does not show up. If anyone could assist I'd greatly appreciate it. Thanx in advance! NOTE: I am trying to output to a ListView column using the ListView_SetItem WIN32 function call.
 
Hi:

minigis is right about the '\n'. When using fgets, I eliminate it. OK, I'm a unix guy, but I would think the following code stub would work under windows:

#include <stdio.h>

int main (void)
{
char buf[10];

fgets(buf, 10, stdin);
if (*buf != '\0')
buf[strlen(buf) - 1] = '\0';

printf("buf is: %s\n", buf);

}
 
It's better to check for the existance of a character before overwriting the position where you 'think' there is one. Remember that there are occasions when fgets() won't put a \n at the end of the string.

Here's another version of the code:

Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
  char buf[BUFSIZ];
  
  if (fgets(buf, sizeof(buf), stdin) != NULL)
  {
    char *p;
    if ((p = strchr (buf, '\n')) != NULL)
    {
      *p = '\0';
    }
    
    printf (">%s<\n", buf);
  }
  
  return(0);
}
There are many other ways to achieve the same result.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top