Ifstream-object outside while-loop - c++

How do I best place the ifstream-object outside the while-loop? If I do as follows the file is only opened once - next time all data is set to zero.
ifstream fil("prices.txt");
while (running) {
// code .... menusystem
// show the file.
}
I know it works if I put the syntax within the while loop but I don't think its a good idea to call this stream-object continiously - am I right?

How do I best place the ifstream-object outside the while-loop?
If you work with the data from that file inside your while loop, it's placed all right.
If I do as follows the file is only opened once - next time all data is set to zero.
It's not clear what data you're talking about. Since you use ifstream, you open the file for reading, and you cannot erase data in it.
Probably you didn't provide all necessary information to judge about your problem.

Related

c++ endless loop reading file created redirecting command output

I'm writing a code in which I check a given directory for new files or directories. New in my situation is regarded to last time the code has been run in that directory. So I create a log file and then I acquire the log in a string vector. The code is the following:
ifstream Finp;
string directory;
vector <string> newfilelist;
system( ("ls -B "+directory+" > "+directory+"filelist.log").c_str() );
Finp.open( (directory+"filelist.log").c_str() );
while ( true ) {
string stmp;
Finp >> stmp;
if( Finp.eof() ) break;
newfilelist.push_back( stmp );
}
Now what's happening is the following:
1) if the log "filelist.log" already exists, everything runs smoothly
2) if the log "filelist.log" does not exist, it is correctly created but when the code opens the file and starts acquiring it, it gets stuck in a loop and the stmp string is endlessly empty (as if the file has no eof() and yet is empty!). what is intresting is the fact that if I place a random system command before opening the log everything runs smoothly!
What am I missing?
I think that, the only thing you would need to change is that nasty while(true) loop to while(file<< to_variable). This would only read data IF there is some.
The eof() is actually quite deceiving. You would guess that it is called right at the end of the file. Though true, when you try to read from the file at the >> operation the pointer in the stream will jump back before the EOF and try to read what is there.
There is quite the few threads here discussing just EOF and using that as a condition for a loop.
If the file does not exist, Finp.open() will basically fail, and checking Finp.eof() is meaningless. Before even attempt to enter a loop to read or check eof, you need to check the Finp status with Finp.good() and then proceed with reading only if this method returns true.

C++: Rename instead of Delete & Copy when using Sync

Currently I have the following part code in my Sync:
...
int index = file.find(remoteDir);
if(index >= 0){
file.erase(index, remoteDir.size());
file.insert(index, localDir);
}
...
// Uses PUT command on the file
Now I want to do the following instead:
If a file is the same as before, except for a rename, don't use the PUT command, but use the Rename command instead
TL;DR: Is there a way to check whether a file is the same as before except for a rename that occurred? So a way to compare both files (with different names) to see if they are the same?
check the md5sum, if it is different then the file is modified.
md5 check sum of a renamed file will remain same. Any change in content of file will give a different value.
I first tried to use Renjith method with md5, but I couldn't get it working (maybe it's because my C++ is for windows instead of Linux, I dunno.)
So instead I wrote my own function that does the following:
First check if the file is the exact same size (if this isn't the case we can just return false for the function instead of continuing).
If the sizes do match, continue checking the file-buffer per BUFFER_SIZE (in my case this is 1024). If the entire buffer of the file matches, return true.
PS: Make sure to close any open streams before returning.. My mistake here was that I had the code to close one stream after the return-statement (so it was never called), and therefore I had errno 13 when trying to rename the file.

MFC C++ Always returning EOF when I have access to file

I am currently stuck in this problem that I do not have any idea to fix. It is regarding a previous question that I have asked here before. But I will reiterate again as I found out the problem but have no idea to fix it.
My program accesses a text file that is updated constantly every millisecond 24/7. It grabs the data line by line and does comparison on each of the line. If any thing is "amiss"(defined by me), then I log that data into a .csv file. This program can be run at timed intervals(user defined).
My problem is that this program works perfectly fine on my computer but yet it doesnt on my clients computer. I have debug the program and these are my findings. Below is my code that I have reduced as much possible to ease the explanation process
int result;
char ReadLogLine[100000] = "";
FILE *readLOG_fp;
CString LogPathName;
LogPathName = Source_Folder + "\\serco.log"; //Source_Folder is found in a .ini file. Value is C:\\phython25\\xyratex\\serco_logs
readLOG_fp = fopen(LogPathName, "r+t");
while ((result = fscanf(readLOG_fp, "%[^\n]\n", ReadLogLine)) != EOF) // Loops through the file till it reaches the end of file
{
Sort_Array(); // Here is a function to sort the different lines that I grabbed from the text file
Comp_State(); // I compare the lines here and store them into an array to be printed out
}
fclose(readLOG_fp);
GenerateCSV(); // This is my function to generate the csv and print everything out
In Sort_Array(), I sort the lines that I grab from the text file as they could be of different nature. For example,
CStringArray LineType_A, LineType_B, LineTypeC, LineTypeD;
if (ReadLogLine == "Example line a")
{
LineType_A.add(ReadLogLine);
}
else if (ReadLogLine == "Example line b")
{
LineType_B.add(ReadLogLine);
}
and so on.
In CompState(), I compare the different values within each LineType array to see if there are any difference. If it is different, then I store them into a seperate array to print. A simple example would be.
CStringArray PrintCSV_Array;
for (int i = 0; i <= LineType_A.GetUpperBound(); i++)
{
if (LineType_A.GetAt(0) == LineType_A.GetAt(1))
{
LineType_A.RemoveAt(0);
}
else
{
LineType_A.RemoveAt(0);
PrintCSV_Array.Add(LineType_A.GetAt(0);
}
}
This way I dont have an infinite amount of data in the array.
Now to the GenerateCSV function, it is just a normal function where I create a .csv file and print whatever I have in the PrintCSV_Array.
Now to the problem. In my client's computer, it seems to not print anything out to the CSV. I debugged the program and found out that it keeps failing here.
while ((result = fscanf(readLOG_fp, "%[^\n]\n", ReadLogLine)) != EOF) // Loops through the file till it reaches the end of file
{
Sort_Array(); // Here is a function to sort the different lines that I grabbed from the text file
Comp_State(); // I compare the lines here and store them into an array to be printed out
}
fclose(readLOG_fp);
It goes into the while loop fine as I did some error checking there in the actual program. The moment it goes into the while loop it breaks out of it suggesting to me it reach EOF for some reason. When that happens, the program has no chance to go into both the Sort_Array and Comp_State functions thus giving me a blank PrintCSV_Array and nothing to print out.
Things that I have checked is that
I definitely have access to the text file.
My thoughts were because the text file is updated every
millisecond, it may have been opened by the other program to write
into it and thus not giving me access OR the text file is always in
an fopen state therefore not saving any data in for me to read. I
tested this out and the program has value added in as I see the KB's
adding up in front of my eyes.
I tried to copy the text file and paste it somewhere else for my
program to read, this way I definitely have full access to it and
once I am done with it, Ill delete it. This gave me nothing to print
aswell.
Am I right to deduce that it is always giving me EOF thus this is
having problems.
while ((result = fscanf(readLOG_fp, "%[^\n]\n", ReadLogLine)) != EOF) // Loops through the file till it reaches the end of file
If yes, How do I fix this?? What other ways can I make it read every line. I have seriously exhausted all my ideas on this problem and need some help in this.
Thanks everyone for your help.
Error is very obvious ... you might have over looked it..
You forgot to open the file.
FILE *readLOG_fp;
CString LogPathName;
LogPathName = Source_Folder + "\\serco.log";
readLOG_fp = fopen(LogPathName.GetBuffer());
if(readLOG_fp==NULL)
cout<<"Error: opening file\n";

QSettings - Sync issue between two process

I am using Qsettings for non gui products to store its settings into xml files. This is written as a library which gets used in C, C++ programs. There will be 1 xml file file for each product. Each product might have more than one sub products and they are written into xml by subproduct grouping as follows -
File: "product1.xml"
<product1>
<subproduct1>
<settings1>..</settings1>
....
<settingsn>..</settingsn>
</subproduct1>
...
<subproductn>
<settings1>..</settings1>
....
<settingsn>..</settingsn>
</subproductn>
</product1>
File: productn.xml
<productn>
<subproduct1>
<settings1>..</settings1>
....
<settingsn>..</settingsn>
</subproduct1>
...
<subproductn>
<settings1>..</settings1>
....
<settingsn>..</settingsn>
</subproductn>
</productn>
The code in one process does the following -
settings = new QSettings("product1.xml", XmlFormat);
settings.setValue("settings1",<value>)
sleep(20);
settings.setValue("settings2", <value2>)
settings.sync();
When the first process goes to sleep, I start another process which does the following -
settings = new QSettings("product1.xml", XmlFormat);
settings.remove("settings1")
settings.setValue("settings3", <value3>)
settings.sync();
I would expect the settings1 to go away from product1.xml file but it still persist in the file - product1.xml at the end of above two process. I am not using QCoreApplication(..) in my settings library. Please point issues if there is anything wrong in the above design.
This is kind of an odd thing that you're doing, but one thing to note is that the sync() call is what actually writes the file to disk. In this case if you want your second process to actually see the changes you've made, then you'll need to call sync() before your second process accesses the file in order to guarantee that it will actually see your modifications. Thus I would try putting a settings.sync() call right before your sleep(20)
Maybe you have to do delete settings; after the sync() to make sure it is not open, then do the writing in the other process?
Does this compile? What implementation of XmlFormat are you using and which OS? There must be some special code in your project for storing / reading to and from Xml - there must be something in this code which works differently from what you expect.

Read from a file when a new line 's been written to it by another process

What is the fastest method in C++, to read a new line from a file which is written by another process. Or how my program can be notified that there is a new line in file so read it? (in linux)
The fastest method is to use pipes or events (for Windows apps).
If you still want use files, first of all that you really need, making sure, that a file has been really modified (use seek and compare it with prew value). Than go to the 'last val of seek' and read it.
And it will be better use mutex (if you read data from file).
Assuming the OS supports concurrent file access, all you should need to do is seek to EOF, wait for the stat to change then try to read from the file. You might want to add in a sleep to slow down the loop.
The 'tail' command on POISX (with the -f option) implements this - source code is available.
From the top of my head, did u tried something like this:
Count the lines in a file, store it.
Get the size of the file (google it, i dont want to ruin the fun :D ).
Then try to read from the last line u stored when size of the file changes... and again and again.
Have fun :)
Use inotify to get notification about file changes and then reread from your last pos if the file is now larger then before.