Thread: How to count the amount of columns or elements in my text file.

  1. #1
    Registered User
    Join Date
    Jan 2020
    Posts
    11

    How to count the amount of columns or elements in my text file.

    Hello all: I am trying to write a code that reads in a text file and then tell me how many column the file has as a integer. The file is a MxN type, where M (rows) is always going to be 81 and N (Columns) can vary from 2 to 42.

    I need to:
    1) read in a text file
    2) determine how many columns there are in the text file

    I am trying to do it by just reading in the first line (since all lines will have the same number of columns) and count the total number of words (columns).


    Code:
    // Initializes line with a maximum of 1500 characters
    char   line[1500];
    
    FILE *fptr3;
    
    int main()
    {
    //Open/Reads file Surrogate Run_Finite_Difference_81.in
    fptr3 = fopen("Surrogate Run_Finite_Difference_81.in","r");  
    
    //stores the first row of the file in "line"
    fgets(line, 1500, fptr3);
    
    //Prints the line to screen 
    printf("%s\n", line);
    
    
    
    //Close Surrogate Run_Finite_Difference_81.in file
     fclose(fptr3);
    
    return 0;
    }
    the output on the screen is correct. It outputs the whole first row for the text file. Which looks something like the line below.

    RunCounter Al[0,0] Al[1,0] Al[2,0] Al[3,0] Al[4,0] Al[5,0] Al[6,0]

    So in this case i would like the code to output a integer of 8 so i can store it as "num" or something for use later. So how do i do this? counting up every time the line encounters a break in characters.

    I've attached the sample file, save it as a .in instead of the .txt it is. Not sure why i couldn't upload the .in version.
    Attached Files Attached Files

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    One way might be to write a function

    Code:
    int countcolumns (const char *s)
    {
        int columns = 0;
        
        while (isspace(*s)) // Skip leading whitespace
            s++;    // Go to next character in string
        while (*s != '\0') {    // While not at end of string
            columns++;
            while (*s != '\0' && !isspace(*s)) {    // While NOT spaces
                s++;    // Go to next character in string
            }
            while (isspace(*s)) // Skip inter-column whitespace
                s++;
        }
        
        return columns;
    }
    and call it on line 17 of your code (pass 'line' to the function after you've read it)

    There's probably a better way to do this but I didn't sleep last night, so...

  3. #3
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    Seems a bit clumsy but it works (*shrug*). Note that it will not work if there are spaces in the column name

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int countcolumns (const char *s);
        
    int main(void)
    {
        const char *str = "      ";    
        const char *line = " RunCounter Al[0,0] Al[1,0] Al[2,0] Al[3,0] Al[4,0] Al[5,0]    Al[6,0]  ";
        
        printf("The string \"%s\"\n    has %d columns\n", str, countcolumns(str));
        printf("The string \"%s\"\n    has %d columns\n", line, countcolumns(line));
    
        return 0;
    }
    
    int countcolumns (const char *s)
    {
        int columns = 0;
        
        while (isspace(*s)) // Skip leading whitespace
            s++;
        while (*s != '\0') {    // While not at end of string
            columns++;
            while (*s != '\0' && !isspace(*s)) {    // While NOT spaces
                s++;    // Go to next character in string
            }
            while (isspace(*s)) // Skip inter-column whitespace
                s++;
        }
        
        return columns;
    }
    output:
    Code:
    The string "      "
        has 0 columns
    The string " RunCounter Al[0,0] Al[1,0] Al[2,0] Al[3,0] Al[4,0] Al[5,0]    Al[6,0]  "
        has 8 columns

  4. #4
    Registered User
    Join Date
    Jan 2020
    Posts
    11
    Wow awesome, this function is exactly what i needed to get the value of the columns thank you. Just a few questions if you have any time to answer them.
    SO i've never made a function in C before so i wanna try to explain what yours does and can you correct if i'm wrong.

    So you create this function called "countcolumns" where it can be executed on a const char *s type. Which is the first line from my file
    It begins with just initializing the columns to zero. The first while statement is saying "While the character is a whitespace character go to the next character"?

    ^^^ Which i don't need because the file doesn't have any leading whitespace. It still worked when i took it out

    And then "While the character string is not terminated add 1 to column" .
    and then "while the character is not terminated and while the character is not a whitespace go to the next character in the string"

    ^^^ so this basically add 1 to column, because its a new string and then continues to the next character in the string until a whitespace appear then the next while loop is initiated

    so then "while the character is a whitespace go to the next character"

    ^^^ so this will continue going to the next character till its not a whitespace and then it repeats the cycle returning the number of columns

  5. #5
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    Quote Originally Posted by Tricica View Post
    Wow awesome, this function is exactly what i needed to get the value of the columns thank you. Just a few questions if you have any time to answer them.
    SO i've never made a function in C before so i wanna try to explain what yours does and can you correct if i'm wrong.

    So you create this function called "countcolumns" where it can be executed on a const char *s type. Which is the first line from my file
    It begins with just initializing the columns to zero. The first while statement is saying "While the character is a whitespace character go to the next character"?

    ^^^ Which i don't need because the file doesn't have any leading whitespace. It still worked when i took it out

    And then "While the character string is not terminated add 1 to column" .
    and then "while the character is not terminated and while the character is not a whitespace go to the next character in the string"

    ^^^ so this basically add 1 to column, because its a new string and then continues to the next character in the string until a whitespace appear then the next while loop is initiated

    so then "while the character is a whitespace go to the next character"

    ^^^ so this will continue going to the next character till its not a whitespace and then it repeats the cycle returning the number of columns
    I'd probably leave the skip leading whitespace part in... just in case

    Yeah what you've written is what it's doing, basically. I'd write it as below but I I think you've got the gist of it

    1. When a non-space character is encountered add 1 to column
    2. Keep skipping (non-whitespace) characters until either the end of the string or a whitespace is encountered
    3. If it's not the end of the string then repeat

  6. #6
    Registered User
    Join Date
    Jan 2020
    Posts
    11
    Hello, I've created a fully functioning code based on your assistance. But I now must adapt it a bit to serve its purpose. Wondering if you still had any tips to assist me.

    Code:
    #include <stdio.h>
    #include <math.h>
    #include <quadmath.h>
    typedef __float128 real;
    typedef __float128 doublereal;
    #include <stdlib.h>
    #include <string.h>
    
    
    //Declare global variables
    char   line[1500], c, r[1500];
    int    i, j, num;
    
    
    FILE *fptr1, *fptr5;
    
    
    int main()
    {
    
    
        // Close and reopen fptr1 to reinitialize the file
        fclose(fptr1);
        fptr1 = fopen("Surrogate_Design_Space_1_Option.in","r");
        fptr5 = fopen("TESTFILE.out", "w");
    // Counts the number of columns the shape function coefficients use in fptr1
        fscanf(fptr1, "%s", line);  //Scans/Stores the First Character "RunCounter" in line
        fgets(line, 1500, fptr1); //Scans/Stores the rest of the first row in line (Over rides last fscanf)
    
    
    
    
        num = countcolumns(line); // Calls function "countcolumns" on character "line" to count the amount of columns in the string
       // printf("The string %s has %d columns\n", line, num); // prints the string thats evaluated above as a check
        printf("Number of columns in fptr1 = %d\n", num); // Prints the Number of columns as a check
    
    
        //Close Surrogate Run_Finite_Difference_81.in file
        fclose(fptr1);
    
    
        return 0;
    }
    int countcolumns (const char *s)
    {
        int columns = 0;
    
    
        printf("Baseline\n");
    
    
        while (isspace(*s)) // Skip leading whitespace
            s++;
            printf("%c", *s);
            fprintf(fptr5, "%c", *s);
        while (*s != '\0') {    // While not at end of string
            columns++;
            while (*s != '\0' && !isspace(*s)) {    // While NOT spaces
                s++;    // Go to next character in string
                printf("%c", *s);
                fprintf(fptr5, "%c", *s);
            }
            while (isspace(*s)) {// Skip inter-column whitespace
                s++;
                printf("\n%c", *s);
                fprintf(fptr5, "\n%c", *s);
            }
        }
        return columns;
    }
    The output is below for this example:
    Al[5,0]
    Au[2,0]
    Au[3,0]
    Au[4,0]
    Au[5,0]
    Au[6,0]
    Au[8,0]
    Au[7,0]
    LDout

    Where i would like:
    Al[5,0] (m)
    Al[5,0] (p)
    Au[2,0] (m)
    Au[2,0] (p)
    Au[3,0] (m)
    Au[3,0] (p)
    Au[4,0] (m)
    Au[4,0] (p)
    Au[5,0] (m)
    Au[5,0] (p)
    Au[6,0] (m)
    Au[6,0] (p)
    Au[8,0] (m)
    Au[8,0] (p)
    Au[7,0] (m)
    Au[7,0] (p)

    So basically i want to be able to write each string of the character "line" twice. duplicating each one and writing the (m) and (p) as shown.

    I haven't attempted (m) and (p) yet because I've been stuck on duplicating for so long. Im not to worried about implementing this. seems straight forward but duplicating is giving me big problems

    I've tried combination of techniques using scanf, fgets, ect. to try and scan the last line created then printing it again. but the output stops at Al[5,0]. Sample below of where i was inserting it. right after the 3rd while loop.

    Code:
    int countcolumns (const char *s)
    {
        int columns = 0;
    
    
        printf("Baseline\n");
    
    
        while (isspace(*s)) // Skip leading whitespace
            s++;
            printf("%c", *s);
            fprintf(fptr5, "%c", *s);
        while (*s != '\0') {    // While not at end of string
            columns++;
            while (*s != '\0' && !isspace(*s)) {    // While NOT spaces
                s++;    // Go to next character in string
                printf("%c", *s);
                fprintf(fptr5, "%c", *s);
            }
            scanf("%s", r);
            printf("hey%s", r);
           // fgets(r, 100, fptr5);
           // printf(" hey %s", r);
          //  printf("%s", *s);
            while (isspace(*s)) {// Skip inter-column whitespace
                s++;
                printf("\n%c", *s);
                fprintf(fptr5, "\n%c", *s);
            }
        }
        return columns;
    }
    Any help would be greatly appreciated!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. copying columns from a text file.
    By alienxx in forum C Programming
    Replies: 2
    Last Post: 12-20-2012, 06:42 AM
  2. Skipping Columns in Text File
    By Vulpecula in forum C++ Programming
    Replies: 3
    Last Post: 08-08-2008, 12:10 PM
  3. read amount of columns per line
    By andone in forum C Programming
    Replies: 12
    Last Post: 12-01-2006, 01:39 AM
  4. reading from a text file a certain amount
    By jodders in forum C++ Programming
    Replies: 2
    Last Post: 02-18-2005, 04:31 AM
  5. how do I count the lines in a text file?
    By slow brain in forum C Programming
    Replies: 4
    Last Post: 03-10-2003, 02:56 PM

Tags for this Thread