Solved

Read data from a file

Posted on 1998-10-13
2
173 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
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
c++ getting the first 10 characters of a char* string 11 94
Raspberry Pi 3 to send text message 9 114
What is sub-make ? 2 60
How to learn Linux? 10 61
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 recursion 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.

773 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