Solved

Read data from a file

Posted on 1998-10-13
2
176 Views
Last Modified: 2010-04-15
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
Comment
Question by:mirado
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 10 total points
ID: 1253497
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
 

Author Comment

by:mirado
ID: 1253498
Thanks jkr!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question