Greetings,

And an advanced "thank you very much" if you can help me :)

I just played with the great tutorial from Dave Sinkula
http://www.daniweb.com/code/snippet151.html

but I'm having trouble altering it.

I want it to read the file, and each one of the lines, and output something like this:

1cat2cat3
1dog2dog3
1bird2bird3

but instead of that I'm getting

1cat
2cat
3
1dog
2dog
3
1bird2bird3

Only the last line is being done correctly. I must change something, but I guess I'm too tired and I didn't figured it out.

Can you help me? File.txt has this:

cat
dog
bird

The code I'm using is:

#include <stdio.h>

int main ( void )
{

  static const char filename[] = "file.txt";
   FILE *file = fopen ( filename, "r" );
   if ( file != NULL )
   {
      char line [ 128 ];

      while ( fgets ( line, sizeof line, file ) != NULL )
      {
printf("1");
fputs ( line, stdout );
printf("2");
fputs ( line, stdout );
printf("3\n");
      
}
      fclose ( file );
   }
   else
   {
      perror ( filename );
   }
   return 0;
}

I've also tried with fputs but the results were the same...

Thank you for your attention :cheesy:

>I've also tried with fputs but the results were the same...
The problem isn't with your output, it's with your input. fgets stores the newline character. Because only the last line isn't terminated with a newline, it's the only line that prints correctly. Try this:

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

int main ( void )
{
  static const char filename[] = "file.txt";
  FILE *file = fopen ( filename, "r" );

  if ( file != NULL )
  {
    char line [ 128 ];

    while ( fgets ( line, sizeof line, file ) != NULL )
    {
      char *newline = strchr ( line, '\n' );

      if ( newline != NULL )
        *newline = '\0';

      printf("1");
      fputs ( line, stdout );
      printf("2");
      fputs ( line, stdout );
      printf("3\n");

    }

    fclose ( file );
  }
  else
  {
    perror ( filename );
  }

  return 0;
}

Thank you!

I will try it :)

It really worked, Narue :)

Thank you! Thank you! Thank you!

It really worked, Narue :)

Yep, Narue's good! Welcome Back!

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.