Thread: File Operations

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    9

    File Operations

    I'm writing this function to read in data from a .txt file containing double variables in the form:

    1.00 2.00
    2.00 3.00

    How do i ensure that any empty lines after [2.00,3.00] doesn't get read in and stored?

    The code below still reads in and store the value.

    Code:
    int read_data(double data[][2]){		// return number of set of data
    	
    	int i=0;
    	
    	FILE *fp;							// File Pointer Declaration
    	fp = fopen("test.txt","r");			// Open the file for reading
    
    	if(fp == NULL)						// If file is empty/not present, print error
    		printf("File Error");	
    	else {
    		while (!feof(fp)){				// Else carry on till end of file is reached
    			fscanf(fp,"%lf",&data[i][0]);
    			fscanf(fp,"%lf",&data[i][1]);
    			printf("\nRow %d %.2lf %.2lf",i,data[i][0],data[i][1]);
    			i++;
    			}
    		}
    
    		fclose(fp);						// Close file 
    		
    	return i-1;								// Numbers of rows returned
    Last edited by meandmyipod; 10-30-2011 at 11:15 AM.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    You read the manual page for fscanf and pay particular attention to the section titled Return Values

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    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. Performing File operations using File Inode number
    By rak1986 in forum C Programming
    Replies: 4
    Last Post: 09-22-2008, 02:43 AM
  2. Help with File operations
    By shwethu in forum C Programming
    Replies: 5
    Last Post: 04-29-2008, 05:52 AM
  3. File operations
    By coo_pal in forum C Programming
    Replies: 2
    Last Post: 05-16-2003, 02:01 AM
  4. File operations?
    By papudi in forum C Programming
    Replies: 11
    Last Post: 05-17-2002, 09:10 PM
  5. File Operations (2)
    By cnealcoc in forum C Programming
    Replies: 2
    Last Post: 04-30-2002, 03:10 PM