Solved

Read data from a file

Posted on 1998-10-13
2
171 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
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 10 total points
Comment Utility
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
Comment Utility
Thanks jkr!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

744 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now