Reading a text file into a string - fread?

This is a discussion on Reading a text file into a string - fread? within the C Programming forums, part of the General Programming Boards category; Hi, I've written a piece of code that should read in a text file, store it in a string, then ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    13

    Reading a text file into a string - fread?

    Hi, I've written a piece of code that should read in a text file, store it in a string, then print it out on screen.

    Code:
    #include<stdio.h>
    
    int main()
    {
    	/*declare and initialise variable*/
    	char text[400];
    	int i=0;
    
    	FILE *file_in;
    	file_in=fopen("text.txt", "r");
    
    	/*stores and prints the data from the string*/
    	fscanf(file_in,"%s", text);
    	printf("%s\n", text);
    
        return 0;
    
    
    }
    Problem I have is that as fscanf doesn't like spaces it won't read a full sentence, it will only print the first word of the file! So 'the quick red fox' comes out as 'the'.

    I'm thinking I need to use something like fread but I'm just not sure how to implement it into the code.

    (I also have another problem, I need to let the user specify the name of the text file, but not sure how. Guessing I need to get a scanf in from the keyboard to put the file name in a variable, but not sure how to apply the content of that variable to the filename section? If anyone could shed any light on that too)

    Thank you!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,499
    Use fgets() to read a text file, one line at a time.

    You can also use fgets() to read from stdin.
    Just read the FAQ on how to deal with the newline at the end, if that is a problem with whatever you want to do next with the input.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you help me about tolower() in file
    By nctar in forum C Programming
    Replies: 7
    Last Post: 05-12-2010, 10:04 AM
  2. Advice reading lines from a text file.
    By Fujitaka in forum C Programming
    Replies: 2
    Last Post: 08-11-2009, 09:43 PM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 10:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21