Member Avatar for die_raupe2

I got this snippet of code from a larger program I've been writing and I'm stuck. All I'm trying to do is read from a file line by line but I keep picking up the new line character, at least that's what I think it is.

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
        FILE *file = fopen(argv[1], "r");
        char buff[128];
        while(fgets(buff, sizeof(buff), file) != NULL)
        {  
                printf("%s\n",buff);
        }
}

Ultimately I want to be able to compare the strings I get from splitting the line.
This is my output from a .txt file:
mangle devoid

devoid systems

systems there

there are

I don't get why the extra new lines inbetween. I'd really appreaciate the help

Recommended Answers

All 3 Replies

The newline is indeed picked up by fgets(). If you think about it, the newline is THE thing that creates or defines a line of text, isn't it?

This will get rid of it:

//add to your include header list:
#include <string.h>   

//in your function where you are reading the lines of text:
char *ptr;

//read your line of text here
while(fgets(buff.... etc.) {
   ptr=strchr(buff, '\n'); //get the address of the newline at the end of the line (or null)
   if(ptr)         //if it was there - if space isn't available in buff[], it won't be there
      *ptr='\0';   //replace it with the end of string char
}

And you're good to go.

There are many ways to do something, and I've always found the four line approach to removing a newline to be excessively verbose. As such, my favorite method of removing a newline is this:

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

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

    while (fgets(buf, sizeof buf, stdin)) {
        buf[strcspn(buf, "\n")] = '\0';
        printf("'%s'\n", buf);
    }

    return 0;
}

In the above code, buf[strcspn(buf, "\n")] = '\0' will assign to the index of the newline if it's present, or the index of the null character at the end of the string if it's not present. So either you're overwriting the newline or it's a no-op by replacing a null character with another null character. This trick turns the removal of a newline at the end of the string into a one-liner.

Member Avatar for die_raupe2

That'll do it. thanks a bunch you guys

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.