Thread: Reading Tab Separted Text files

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    1

    Question Reading Tab Separted Text files

    I am having a problem in reading a text file in which data is written in columnar format seperated by tabs
    like
    1 10 100
    2 15 200

    and i am using the following code using fscanf but when it encounters tab it enters a end of line character

    #include <stdio.h>

    int main()
    {
    FILE *textfile;
    char line[80];
    char Templine[80];

    clrscr();

    if( (textfile=fopen("test.txt", "r")) == NULL )
    {
    printf ("Error opening text file for reading\n");
    exit(0);
    }

    /*read file contents*/
    while( (fscanf(textfile, "\t %s", Templine) != EOF) )
    {
    if (strchr("\n",Templine) == NULL)
    line[0] = strcat(line, Templine);
    else
    line[0] = "\0";

    printf ("%s\n", line);
    }


    /*close the file*/
    fclose(textfile);
    getch();
    }

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    Perhaps you should remove the \t from the formatstring. I'm not sure, but aren't tabs in text-files replaced by spaces? In that case you only need %d to read integer values. Personally I would use %d to get the integer values instead of reading the whole line as a string.

    I guess something like this should work:

    Code:
    FILE *textfile;
    int a, b, c;
    
    fscanf(textfile, "%d%d%d", &a, &b, &c);
    By the way, you forgot to return a return value at the end of main. And I would not use exit(0). But do something like:

    Code:
    if ((textfile=fopen("test.txt", "r")) == NULL) 
    { 
        printf ("Error opening text file for reading\n"); 
        return_value = 0; 
    }
    else
    {
        /* file is opened for reading */
        
        ....
    
        return_value = 1;
    }
    
    return return_value;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading from text file
    By jamez in forum C Programming
    Replies: 3
    Last Post: 11-30-2005, 07:13 PM
  2. How to use FTP?
    By maxorator in forum C++ Programming
    Replies: 8
    Last Post: 11-04-2005, 03:17 PM
  3. Reading binary files and writing as text
    By thenrkst in forum C++ Programming
    Replies: 8
    Last Post: 03-13-2003, 10:47 PM
  4. displaying text files, wierd thing :(
    By Gades in forum C Programming
    Replies: 2
    Last Post: 11-20-2001, 05:18 PM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM