Thread: Reading in CSV file

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    11

    Reading in CSV file

    I have written this code to read in a CSV file. It is compiling fine, but the a.out file is telling me the file does not exist. I have double checked file name and location but all seems in order. Am I doing something wrong with the code itself?

    Code:
    int main ( void )
    {
    /*file type warning*/
    printf ("Please make sure the file is in CSV format before continuing.\n");
    	
    /*ask for file name */
    char filename [128] ;
    fputs ("Enter the filename: ", stdout) ;
    fflush(stdout) ;
    fgets(filename, sizeof filename, stdin ) ;
    
    /*create file pointer*/
    FILE *fp ;
    
    /*open file*/
    fp = fopen (filename, "r") ;
    int row, column ;
    
    /*read file*/
    char arra [6] [2000] ;
    char line [2000];
    
    for( row = 0; row < 5; row++ )	
    for( column = 0; column < 2000; column++ )
    arra [row] [column] = '\0' ;
    
    for (row = 0; row < 5; row++)
    line [row] = '\0' ;
    
    if ( fp != NULL)
    {
    
    row = 0 ;
    
    while (fgets (line, sizeof line, fp ) != NULL) /*read a line*/
    {
    strcpy (arra[row], line) ;
    printf ("array --> %s", &arra[row]) ;
    row++;
    }
    fclose(fp) ;
    }
    else
    {
    perror( filename) ;
    }
    The code goes on after this, I know the main function isn't closed.

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    You probably have a new line on the end of "filename", since fgets() also reads in the new line character.

    You can remove it as such:
    Code:
    char * nl = NULL;
    
    /* ... */
    nl = strchr(filename, '\n');
    if(nl)
    {
       *nl = '\0';
    }
    PS: A bit of indenting wouldn't hurt.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    11
    Thanks, it works now. Sorry about the indents, they disappeared when I copy-pasted into the browser.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

Tags for this Thread