LinuxQuestions.org
Visit Jeremy's Blog.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices



Reply
 
Search this Thread
Old 06-26-2008, 03:13 PM   #1
gkoumantaris
LQ Newbie
 
Registered: Jun 2008
Posts: 5

Rep: Reputation: 0
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;

}
 
Old 06-26-2008, 04:15 PM   #2
rubadub
Member
 
Registered: Jun 2004
Posts: 233

Rep: Reputation: 33
for every line you get you could split it using strtok delimiting with a space...
 
Old 06-27-2008, 11:32 AM   #3
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,396
Blog Entries: 2

Rep: Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903
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.

Last edited by theNbomr; 06-27-2008 at 04:47 PM.
 
Old 06-27-2008, 04:32 PM   #4
gkoumantaris
LQ Newbie
 
Registered: Jun 2008
Posts: 5

Original Poster
Rep: Reputation: 0
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,
 
Old 06-28-2008, 10:11 AM   #5
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian
Posts: 2,541

Rep: Reputation: 878Reputation: 878Reputation: 878Reputation: 878Reputation: 878Reputation: 878Reputation: 878
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.
 
Old 06-30-2008, 02:37 PM   #6
gkoumantaris
LQ Newbie
 
Registered: Jun 2008
Posts: 5

Original Poster
Rep: Reputation: 0
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 */



Last edited by gkoumantaris; 06-30-2008 at 02:45 PM.
 
Old 06-30-2008, 06:25 PM   #7
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,396
Blog Entries: 2

Rep: Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903
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.
 
Old 07-01-2008, 11:05 AM   #8
rubadub
Member
 
Registered: Jun 2004
Posts: 233

Rep: Reputation: 33
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
 
Old 07-01-2008, 11:15 AM   #9
sk8guitar
Member
 
Registered: Jul 2003
Location: DC
Distribution: mandrake 9.1
Posts: 415

Rep: Reputation: 30
Thumbs up

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.
 
Old 07-01-2008, 11:15 AM   #10
sk8guitar
Member
 
Registered: Jul 2003
Location: DC
Distribution: mandrake 9.1
Posts: 415

Rep: Reputation: 30
granted its mostly c++ psuedocode but you get the gist of whats going on i'm sure
 
Old 07-01-2008, 11:53 AM   #11
tronayne
Senior Member
 
Registered: Oct 2003
Location: Northeastern Michigan, where Carhartt is a Designer Label
Distribution: Slackware 32- & 64-bit Stable
Posts: 3,119

Rep: Reputation: 818Reputation: 818Reputation: 818Reputation: 818Reputation: 818Reputation: 818Reputation: 818
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);
}
 
Old 07-01-2008, 12:45 PM   #12
gkoumantaris
LQ Newbie
 
Registered: Jun 2008
Posts: 5

Original Poster
Rep: Reputation: 0
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.
 
Old 07-01-2008, 01:38 PM   #13
gkoumantaris
LQ Newbie
 
Registered: Jun 2008
Posts: 5

Original Poster
Rep: Reputation: 0
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
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
C++ text file line by line/each line to string/array Dimitris Programming 15 03-11-2008 09:22 AM
php - Read file line by line and change a specific line. anrea Programming 2 01-28-2007 02:43 PM
read line by line form text file in java. spank Programming 1 10-18-2006 03:46 PM
linux scripting help needed read from file line by line exc commands each line read atokad Programming 4 12-26-2003 11:24 PM


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

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration