Guys need some help,
I am making a script to read the latest from a text file. the script already does this but I'm kind of lost to adjust some things
He picks up the line by numbytes in fseek, but the data line may vary and numbytes not be accurate, how can I fix this?
And another problem is that the line has, date, time, value, separated by space, how to read that line and put these 3 information in variable?
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *arq;
char Line[100];
char *result;
int tam, i;
// Opens a file for READING TEXT
arq = fopen("temp.txt", "rt");
if (arq == NULL) // If there was an error in opening
{
printf("Problems opening file\n");
return 2;
}
// Read last line text file
tam= -25;
fseek(arq, tam, SEEK_END);
i = 1;
while (!feof(arq))
{
result = fgets(Line, 100, arq);
if (result) // If it was possible to read the report online content
printf("%d : %s",i,Line);
i++;
}
fclose(arq);
}
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
char * data1,data2,data3;
fstream file; // If you don't know what std::fstream is, look it up
file.open("temp.txt");
if(!file.is_open())
{
cout << "Problem opening file.\n";
return 2;
}
file.seekg(EOF); // go to the end of file
while(true)
{
file.unget(); //go back two chars
file.unget();
char in = file.get();
if(in == '\n')
{
//get line from file until space is encountered and put it in data1
file.getline(data1,' ');
file.getline(data2,' '); //etc
file.getline(data3,' ');//etc
break;
}
}
//send the data to the output stream
cout << "Data: " << data1 << " " << data2 << " " << data3 << endl;
//end program
return 0;
}
I pretty much typed this up in my browser, not guarranteed to work, but pretty sure it does. Hope this helps!
Thanks cire for the correction.
This (should) work for splitting the data into three vars.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
string vars[3];
int whichVar = 0;
for(unsignedint i = 0; i < line.size(); i++)
{
if(!line[i] == ' ')
{
vars[whichVar] += line[i]; //add the non-space char to the current
//variable }
else
{
whichVar++; //switch the variable being used
}
}
This will only work as long as there are no spaces besides the separating ones. This will work if there is only two data members as well. or five, six, or seven, just change the size of the array.
for me at least I think I got a better way to split the data, however I am having trouble splitting time and value, I do not think one way of defining reliable, can you help me?