Thread: Reading a written string from a file

  1. #1
    Registered User
    Join Date
    Apr 2011
    Location
    Melbourne, Australia
    Posts
    6

    Reading a written string from a file

    Hi, Just wondering how to read a string I have written to this file, for verification that it was written to the file. If I do printf and read c string, it isn't verifying it was written to the file.
    Code:
    #include <stdio.h>
    #define FILENAME "data.txt"
    
    int main(void)
    {
    	char rating[20]="Good";
    
    	FILE *data_1;
    
    	data_1 = fopen("data","w");
    	
    	if(data_1==NULL)
    	printf("error Opening file");
    	
    	else
    	{
    		fprintf(data_1,"%s", rating); /* writes the c string rating to file*/
    	}
    	/* don't know how to print what is in datafile to screen*/
    	
    	fclose(data_1);
    	return 0;
    	
    }
    Cheers

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    You want to read(only) from a file so you have to type
    Code:
    data_1=fopen("data","r");

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    278
    Why not close the file, then open it again, read what's in it into an array/string, and then print it?

  4. #4
    Registered User
    Join Date
    Apr 2011
    Location
    Melbourne, Australia
    Posts
    6
    So there is no way to read directly from a file, I must open then feed it into an array, then read string into array?

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    If you open the file in "w+" mode... you can write to it, seek() back to the beginning, and read it back into a string.
    If you write more than one line, it's a bit more complex but the concept is the same.

    However... if you told it to write and got no run time errors, you can trust it's written. Most OSs will tell you about disk errors.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading string from a file
    By kuma0177 in forum C Programming
    Replies: 1
    Last Post: 02-05-2010, 06:58 PM
  2. reading int and string from file fscanf
    By awesmesk8er in forum C Programming
    Replies: 5
    Last Post: 02-12-2009, 04:01 PM
  3. Reading IDL CORBA objects written from java
    By dpro in forum C++ Programming
    Replies: 10
    Last Post: 01-25-2006, 03:27 PM
  4. Reading a file written by VB
    By nemaroller in forum C++ Programming
    Replies: 8
    Last Post: 07-12-2002, 11:17 PM
  5. reading file into a string array
    By lambs4 in forum C Programming
    Replies: 7
    Last Post: 01-22-2002, 04:23 PM