Thread: Reading a text file into a string - fread?

  1. #1
    Registered User
    Join Date
    Nov 2010

    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.

    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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    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.

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
Website Security Test