[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 179
  • Last Modified:

Read data from a file

I need to read an entire line of text from a file. How can this be done. I tried to use the fscanf function but this stops after the first word in the first line. For example:
I want to be able to read "This is the first line of text" and store it into a string value.

What I'm wanting to do is add several lines of text to an existing text file. I was going to create a new file with my inserted text at the top of the file and then read from the existing file and print all data that was read to the new file after the newlines.

Hopefully there is a better way...

Thanks
0
mirado
Asked:
mirado
1 Solution
 
jkrCommented:
To read an entire line, use the 'fgets()' function, e.g.

/* FGETS.C: This program uses fgets to display
 * a line from a file on the screen.
 */

#include <stdio.h>

void main( void )
{
   FILE *stream;
   char line[100];

   if( (stream = fopen( "fgets.c", "r" )) != NULL )
   {
      if( fgets( line, 100, stream ) == NULL)
         printf( "fgets error\n" );
      else
         printf( "%s", line);
      fclose( stream );
   }
}

(Example form the VC5 docs on 'fgets()')
0
 
miradoAuthor Commented:
Thanks jkr!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now