LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   help with c program to read each line from text file, split line , process and output (http://www.linuxquestions.org/questions/programming-9/help-with-c-program-to-read-each-line-from-text-file-split-line-process-and-output-651881/)

gkoumantaris 06-26-2008 02:13 PM

help with c program to read each line from text file, split line , process and output
 
hello , here is what i have until now:
here is a sample line on my text file

1000 234 235 234 1000 9000 988 7877 122 234 233

need to assign variables on all numbers and output result in a similar way.

any ideas?
thank you in advance.

#include <stdio.h>



int main ( void )

{

static const char filename[] = "testingcelebpoints.txt";

FILE *file = fopen ( filename, "r" );


if ( file != NULL )

{

char line [ 128 ]; /* or other suitable maximum line size */



while ( fgets ( line, sizeof line, file ) != NULL ) //read a line



{

fputs ( line, stdout ); /* write the line */

}

fclose ( file );

}

else

{

perror ( filename ); /* why didn't the file open? */

}

return 0;

}

rubadub 06-26-2008 03:15 PM

for every line you get you could split it using strtok delimiting with a space...

theNbomr 06-27-2008 10:32 AM

Please post source code in [CODE] tags so we can all read it the way you wanted it to look.
Your one-line sample leaves some questions. If all lines in the file contain the same formatting with respect to the number of whitespace-delimited numeric fields, then fscanf() is your easiest route.
Code:

    assignments = fscanf( file, "%d %d %d %d %d %d %d %d %d %d %d",
                                &var0, &var1, &var2, &var3, &var4, &var5,
                                      &var6, &var7, &var8, &var9, &var10 );
    if( assignments < 11 ){
        fprintf( stderr, "Oops: only %d fields read\n", assignments );
    }

--- rod.

gkoumantaris 06-27-2008 03:32 PM

thanks guys
 
i ended up working out a different not so C like solution but i am still stuck.
look at this now:
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>

int main()
{
std::ifstream f("myfile.txt");

// Read all lines
std::string line;
while(std::getline(f, line))
{
//assign variables to values
std::istringstream tmp(line);
std::string pic,tl1,tl2,br1,br2,le1,le2,re1,re2,n1,n2,m1,m2;
tmp >> pic>>tl1>>tl2>>br1>>br2>>le1>>le2>>re1>>re2>>n1>>n2>>m1>>m2;

//here i need to convert to int and work on the variables to output a new textfile with different data.//


//out ..
std::cout << whatever variable you want << "\n";
}
}

i tried using atoi but i can not make it work with the string file.

thank you for your help,

ntubski 06-28-2008 09:11 AM

C++ streams will convert to int when reading to an int variable.
Code:

int pic,tl1,tl2,br1,br2,le1,le2,re1,re2,n1,n2,m1,m2;
tmp >> pic>>tl1>>tl2>>br1>>br2>>le1>>le2>>re1>>re2>>n1>>n2>>m1>>m2;

Please post in [code] tags, as in

[code] your code here [/code]

and don't use yellow text, it's unreadable.

gkoumantaris 06-30-2008 01:37 PM

here is a line from my data file:
elton5.jpg 282 114 365 214 294 150 332 150 309 171 317 194


i used your suggestion, thank you .
but my numbers do not make any sense?any ideas why?

PHP Code:

while ( fgets linesizeof linefile ) != NULL //read a line

{
fscanffile"%d %d %d %d %d %d %d %d %d %d %d %d %d",&var0, &var1, &var2, &var3, &var4, &var5,&var6, &var7, &var8, &var9, &var10, &var11, &var12);



printf("formatted line: %d %d %d \n",1,var1+var3,var2+var4);



fputs linestdout ); /* write the line */




theNbomr 06-30-2008 05:25 PM

Code:

printf("formatted line: %d %d %d \n",1,var1+var3,var2+var4);
You have specified three integer variables to be printed in your format string, but only two are given as arguments. This will result in undefined behavior.
--- rod.

rubadub 07-01-2008 10:05 AM

aren't fputs, fgets and fscanf all C functions?

Digressing back to his second example (first c++), it should go a little like this:
Code:


int main()
{
        std::ifstream file;
        file.open("test.txt");
       
        std::string pic;
        int var1,var2,var3,var4,var5,var6,var7,var8,var9,var10,var11,var12;
       
        file >> pic >> var1 >> var2 >> var3 >> var4 >> var5 >> var6 >> var7 >> var8 >> var9 >> var10 >> var11 >> var12;
        printf("formatted line: %d %d %d \n",1,var1+var3,var2+var4);
}

using a file with:
Quote:

elton5.jpg 282 114 365 214 294 150 332 150 309 171 317 194

sk8guitar 07-01-2008 10:15 AM

why not do something along the lines of

Code:


vector<string> fileVector;
while(!file.EOF){
    string temp;
    cin >> temp;
    fileVector.push(temp);
}

or if you wanted to be strictly C malloc an array and reallocate it when you approach the limit of how much you have allocated for.

whatever you do you should probably use a dynamic storage mechanism, unless you know that you will ALWAYS have the same number or less of elements per line.

sk8guitar 07-01-2008 10:15 AM

granted its mostly c++ psuedocode but you get the gist of whats going on i'm sure

tronayne 07-01-2008 10:53 AM

Here's a example program that will parse as many lines of text you have in one or more files; it displays the tokens (individual "word") on the standard output although you could assign a token to a variable if that suits your needs. It's C -- not C++ -- but there you are. Hope it helps some.
Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#ifndef TRUE
#      define  TRUE    1
#endif
#ifndef FALSE
#      define  FALSE  0
#endif

int    main    (int argc, char *argv [])
{
        char    buf [BUFSIZ];          /* a buffer                    */
        char    *tokptr, *strptr = buf; /* a pointer to the buffer      */
        int    c;                      /* general-purpose              */
        int    error = FALSE;          /* error flag                  */
        int    vopt = FALSE;          /* verbose option              */
        FILE    *in;                    /* input file                  */

        /*      process the command line arguments                      */
        while ((c = getopt (argc, argv, "?v")) != EOF) {
                switch (c) {
                case '?':
                        error = TRUE;
                        break;
                case 'v':
                        vopt = TRUE;
                        break;
                default:
                        (void) fprintf (stderr, "getopt() bug\n");
                        exit (EXIT_FAILURE);
                }
        }
        /*      any errors in the arguments, or a '?' entered...*/
        if (error) {
                (void) fprintf (stderr, "usage: %s [-v] input_file...\n",
                    argv [0]);
                exit (EXIT_FAILURE);
        }
        /*      now process any arguments supplied...  */
        while (optind != argc) {
                if (vopt) {
                        (void) fprintf (stderr, "Processing %s...\n", argv [optind]);
                }
                /*      open the input file            */
                if ((in = fopen (argv [optind], "r")) == (FILE *) NULL) {
                        (void) fprintf (stderr, "%s:\tcan't open %s\n", argv [0], argv [optind]);
                        exit (EXIT_FAILURE);
                }
                /*      get a line from the input file  */
                while (fgets (buf, sizeof (buf), in) != (char *) NULL) {
                        /*      we have to point to buf */
                        strptr = buf;
                        /*      take the line apart    */
                        while ((tokptr = strtok (strptr, " \n")) != (char *) NULL) {
                                /*
                                *      could assign tokptr to a varialbe here
                                *      instead of just displaying it
                                */
                                (void) fprintf (stdout, "%s\n", tokptr);
                                /*      null the pointer        */
                                strptr = (char *) NULL;
                        }
                }
                /*      close the input file            */
                if (fclose (in))
                        (void) fprintf (stderr, "%s:\tcan't close %s\n", argv [0], argv [optind]);
                /*      bumpt the counter for next file */
                optind++;
        }
        return (0);
}


gkoumantaris 07-01-2008 11:45 AM

it is working now with your help but..
 
here is the code.
it works fine until the 15th line.
after that the loop stops. i did not take a look at it yet.
i will post the code when its debuged.


[HTML]int main()
{
std::ifstream file;
file.open("my file");

// Read all lines
std::string line;

while(std::getline(file, line))
{
std::istringstream tmp(line);
std::string pic;
int var1,var2,var3,var4,var5,var6,var7,var8,var9,var10,var11,var12;

file >> pic >> var1 >> var2 >> var3 >> var4 >> var5 >> var6 >> var7 >> var8 >> var9 >> var10 >> var11 >> var12;
printf("formatted line:%d %d %d \n",1,(var1+var3)/2,(var2+var4)/2);

}
}[/HTML]

thank you all for your help.

sorry for jumbing from c to c++.
you are the best.

gkoumantaris 07-01-2008 12:38 PM

here it is
 
here is the complete code:


[HTML]#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include <cstdlib>


int main()
{
std::ifstream f("testing-all-sunglasses.txt");

// Read all lines
std::string line;

while(std::getline(f, line))
{

//assign values to variables
std::istringstream tmp(line);
std::string pic;
float tl1,tl2,br1,br2,le1,le2,re1,re2,n1,n2,m1,m2;
tmp >> pic>>tl1>>tl2>>br1>>br2>>le1>>le2>>re1>>re2>>n1>>n2>>m1>>m2;


//out ..
std::cout <<1<<" "<< (tl1+br1)/2 <<" "<<(tl2+br2)/2 <<" "<< "\n";
}

}[/HTML]
thank you all for your help.
that was my first post on these forums so forgive me for my mistakes.

i will try to give back the time you spend on my program to the forum .

thanks


All times are GMT -5. The time now is 09:09 AM.