How to Read and write into/from a text file? - windows

Please correct the below code:only.
file already contains entries : 1st row username; 2nd row password.
checkbox status required to write to the third line and need to read or alter only the checkbox status value in the file.
Currently this code is working if there already is a value for the checkbox status value, then it is overwriting, else UI is hanging.
WriteCheckStatusToFile(BOOL& locVar)
{
FILE *l_pFile = NULL;
CString l_strRememberCheck;
l_strRememberCheck = GetExePath() + _T("password");
CString sVar;
sVar.Format(_T("%d"),locVar);
if(NULL != (l_pFile = fopen(l_strRememberCheck, _T("r+"))) )
{
int count = 0;
char c;
while(count != 2)
{
if((c = fgetc(l_pFile)) == '\n') count++;
}
fseek(l_pFile,ftell(l_pFile),SEEK_SET);
fprintf(l_pFile, sVar);
}
l_strRememberCheck.ReleaseBuffer();
fclose(l_pFile);
}
thanks in advance to all!
sam.

This line
fprintf(l_pFile, sVar);
doesn't look right. I think it should be
fprintf(l_pFile, "%s\n", (LPCTSTR) sVar);
The loop could become infinite if the file has less than two linefeeds:
while(count != 2)
I think it should be:
while( (count < 2) && ( ! feof(l_pFile) ) && ( c != EOF ) )
Probably unrelated to your error, but - at least for this code snippet - CString::ReleaseBuffer() doesn't need to be called since you have not called CString::GetBuffer().
l_strRememberCheck.ReleaseBuffer();
This line may be unnecessary as it appears to fseek() to where the file pointer already is:
fseek(l_pFile,ftell(l_pFile),SEEK_SET);
In the event a two-line file is not terminated with a '\n' you would need to print like this:
if ( count == 2 )
{
fprintf(l_pFile, "%s\n", (LPCTSTR) sVar);
}
else
{
fprintf(l_pFile, "\n%s\n", (LPCTSTR) sVar);
}

Related

PVS-Studio: warning V595 is generated even if pointer is checked

In the following code there is already check for nullptr in (1):
int msg;
struct x * var[2];
if ((var[0] = get_x()) == nullptr) { // (1)
return;
}
if (var[0]->data != 11) { // (2) <<< V595
msg = 1;
printf("msg1");
}
if (var[0] && var[0]->data == 12) { // (3) <<< V595
msg = 2;
return;
}
but I still get error: V595. Why?
I agree that there is an exceeding check for nullptr in (3).
Analyzer considers this piece of code abnormal. First, the pointer is being deferenced, and after that it is being verified. Even if it cannot be equal to NULL, it looks very suspicious. There's a possibility that wrong variable is used or checked.
So it is possible that the wrong variable is used, and the corrected version of code could look like:
if (FOO->data != 11) {
msg = 1;
printf("msg1");
}
if (var[0] && var[0]->data == 12) {
msg = 2;
return;
}
Or, probably, the condition is incorrect:
if (var[0]->data != 11) {
msg = 1;
printf("msg1");
}
if (FOO && var[0]->data == 12) {
msg = 2;
return;
}
Anyway, the analyzer doesn't like it, and it issues a warning. To eliminate such warnings, remove unnecessary checks which overload the code and confuse other programmers and the analyzer. In this case the analyzer will not issue the warning:
if ((var[0] = get_x()) == nullptr) {
return;
}
if (var[0]->data != 11) {
msg = 1;
printf("msg1");
}
if (var[0]->data == 12) {
msg = 2;
return;
}
If you don't want to remove this check, use one of the following ways to suppress warnings:
Suppression of false alarms
Mass Suppression of Analyzer Messages

MQL5: how do I automatically delete all un-triggered pending orders before placing new orders?

I am working on a Project that requires me to place a BUYSTOP and a SELLSTOP pair of orders and then on the next bar if those orders are not triggered, then delete them and place fresh ones.
Here is my code:
if(logic == true && OrdersTotal() == 0)
{bool res = OrderSend(....);}
if(OrdersTotal() != 0)
{
if(ordertype == OP_BUY || ordertype == OP_SELL)
{
bool del = OrderDelete(....);
}
}
This code is properly placing orders and deleting them as well when I am testing.
But when the EA is active on the live server, it does not open orders because the platform already has orders of other instruments open.
I'm sure there would be quite an easy way to get around this but since I am a novice, I'm not able to figure that out.
it is not clear whether you use magic number and symbol check.
you should check sth like
int _ordersTotal = OrdersTotal()-1;
for (int i = _ordersTotal; i >= 0; i--){
if (OrderSymbol() != Symbol() || OrderMagicNumber() != magic) continue;
....
}
in different realization, i.e. you can create a function(String Symbol) that checks if you have some working orders placed of the indicated Symbol.
Old proverb says:Measure twice before cut onceThere are actually four values ( three for pendings ) to check before OrderDelete()
As your definition states to handle { OP_{BUY|SELL}STOP } orders, there are following three items to check:
Symbol() match ( not causing unwanted side-effects by deleting other EA's or manual orders )
OrderType() match ( not ignoring the actual state { PENDING | AT_MARKET } and direction { BUY | SELL } of the order )
OrderMagicNumber() match ( not ignoring the UUID selector utility available to be set for each individual OrderSend() )
So, let's sketch the detection process:
int myEaContextAwareMagicNUMBER = ...;
for ( int ii = OrdersTotal();
ii >= 0;
ii--
)
if OrderSelect( ii, SELECT_BY_POS, MODE_TRADES )
{
if ( OrderSymbol() != _Symbol
&& OrderMagicNumber() != myEaContextAwareMagicNUMBER
&& OrderOpenTime() >= Time[1] // Prev. Bar
&& !( OrderType() == OP_BUYSTOP
|| OrderType() == OP_SELLSTOP
)
) continue; // __^ __^ __^ __^ __^ __^ loop for next test
// -------------------------------------------+
// FINALLY PROCESS THE MATCHING OrderDelete() |
// -------------------------------------------+
...
..
.
// -------------------------------------------+
}
else Print( "WARN: OrderSelect() failed at db.POOL.SELECT(), RECORD_NUMBER == ", ii );
So how to delete un-triggered pendings is done.
Next comes the remark about
"... when the ea is active on the live server, it does not open orders because the platform already has orders of other instruments open."
There could hardly be any advice provided without delivering the exact { GetLastError() | _LastError } values.
Some Brokers for some account types do indeed restrict OrderSend() acceptance policies, and thus besides the GetLastError() value the respective Broker Terms and Conditions apply.
Do not hesitate to ask more & may enjoy other Questions/Answers in MQL4 domain.

error not all control paths return a value

My compiler says that not all control paths return a value and it points to a overloaded>> variable function. I am not exactly sure what is causing the problem and any help would be appreciated. I am trying to overload the stream extraction operator to define if input is valid. if it is not it should set a failbit to indicate improper input.
std::istream &operator >> (std::istream &input, ComplexClass &c)//overloading extraction operator
{
int number;
int multiplier;
char temp;//temp variable used to store input
input >> number;//gets real number
// test if character is a space
if (input.peek() == ' ' /* Write a call to the peek member function to
test if the next character is a space ' ' */) // case a + bi
{
c.real = number;
input >> temp;
multiplier = (temp == '+') ? 1 : -1;
}
// set failbit if character not a space
if (input.peek() != ' ')
{
/* Write a call to the clear member function with
ios::failbit as the argument to set input's fail bit */
input.clear(ios::failbit);
}
else
// set imaginary part if data is valid
if (input.peek() == ' ')
{
input >> c.imaginary;
c.imaginary *= multiplier;
input >> temp;
}
if (input.peek() == '\n' /* Write a call to member function peek to test if the next
character is a newline \n */) // character not a newline
{
input.clear(ios::failbit); // set bad bit
} // end if
else
{
input.clear(ios::failbit); // set bad bit
} // end else
// end if
if (input.peek() == 'i' /* Write a call to member function peek to test if
the next character is 'i' */) // test for i of imaginary number
{
input >> temp;
// test for newline character entered
if (input.peek() == '\n')
{
c.real = 0;
c.imaginary = number;
} // end if
else if (input.peek() == '\n') // set real number if it is valid
{
c.real = number;
c.imaginary = 0;
} // end else if
else
{
input.clear(ios::failbit); // set bad bit
}
return input;
}
}
The return statement is only executed inside the last if:
if (input.peek() == 'i' ) {
...
return input;
}
It should be changed to:
if (input.peek() == 'i' ) {
...
}
return input;

How to correctly exit a for loop and run the next conditional statement

UPDATE: Thank you for the help. Writing a demo that you could run did help me solve the issue but not in the way that I expected. I think this is a compiler optimization rather than a bug. When the code inside if ( z == true ) is commented out, the conditional statement is skipped entirely and the control returns to if (x). If I put actual code in, we hit the conditional statement when appropriate.
ORIGINAL QUESTION:
I have a std::string and I am iterating through it to determine whether it contains certain characters. If any of these characters are found, I want to exit the for loop and proceed with the next conditional statement. Here is an example:
#include <iostream>
using namespace std;
int main()
{
bool x = true;
bool y = true;
bool z = true;
std::string str;
cout << "Enter string: ";
cin >> str;
if ( x )
{
if ( y )
{
std::string::iterator i;
for ( i = str.begin(); i != str.end(); i++ )
{
cout << "Enter for" << endl;
if ( *i == 'a' || *i == 'b' || *i == 'c' )
{
z = false;
cout << "Exit for" << endl;
break;
}
}
if ( z == true )
{
//cout << "z == true" << endl;
}
}
}
}
The issue is that the program never hits if (z == true). When it breaks out of the loop, control returns to the first conditional statement ( if (x) ).
I tried removing the break and instead setting i = ( str.end() - 1 ). This resulted in the same behavior - it goes back to the for, determines that it's at the last character of the string, and then returns control to the first conditional statement again, skipping the if ( z == true ) as intended.
What am I doing wrong here?
"When it breaks out of the loop, control returns to the first conditional statement ( if (something) )."
When it breaks out of the loop, it has just set b to false, so the if (b == true) code won't run. What am I misunderstanding?
Edit: I think you have oversimplified your code. Clearly that's not the code you're actually running because str never has a value. You need to post an example that we can actually run (but once you have created such an example, you'll probably find the error for yourself. :-) )

text box percentage validation in javascript

How can we do validation for percentage numbers in textbox .
I need to validate these type of data
Ex: 12-3, 33.44a, 44. , a3.56, 123
thanks in advance
sri
''''Add textbox'''''
<asp:TextBox ID="PERCENTAGE" runat="server"
onkeypress="return ispercentage(this, event, true, false);"
MaxLength="18" size="17"></asp:TextBox>
'''''Copy below function as it is and paste in tag..'''''''
<script type="text/javascript">
function ispercentage(obj, e, allowDecimal, allowNegative)
{
var key;
var isCtrl = false;
var keychar;
var reg;
if (window.event)
{
key = e.keyCode;
isCtrl = window.event.ctrlKey
}
else if (e.which)
{
key = e.which;
isCtrl = e.ctrlKey;
}
if (isNaN(key)) return true;
keychar = String.fromCharCode(key);
// check for backspace or delete, or if Ctrl was pressed
if (key == 8 || isCtrl)
{
return true;
}
ctemp = obj.value;
var index = ctemp.indexOf(".");
var length = ctemp.length;
ctemp = ctemp.substring(index, length);
if (index < 0 && length > 1 && keychar != '.' && keychar != '0')
{
obj.focus();
return false;
}
if (ctemp.length > 2)
{
obj.focus();
return false;
}
if (keychar == '0' && length >= 2 && keychar != '.' && ctemp != '10') {
obj.focus();
return false;
}
reg = /\d/;
var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
return isFirstN || isFirstD || reg.test(keychar);
}
</script>
You can further optimize this expression. Currently its working for all given patterns.
^\d*[aA]?[\-.]?\d*[aA]?[\-.]?\d*$
If you're talking about checking that a given text is a valid percentage, you can do one of a few things.
validate it with a regex like ^[0-9]+\.?[0-9]*$ then just convert that to a floating point value and check it's between 0 and 100 (that particular regex requires a zero before the decimal for values less than one but you can adapt it to handle otherwise).
convert it to a float using a method that raises an exception on invalid data (rather than just stopping at the first bad character.
use a convoluted regex which checks for valid entries without having to convert to a float.
just run through the text character by character counting numerics (a), decimal points (b) and non-numerics (c). Provided a is at least one, b is at most one, and c is zero, then convert to a float.
I have no idea whether your environment support any of those options since you haven't actually specified what it is :-)
However, my preference is to go for option 1, 2, 4 and 3 (in that order) since I'm not a big fan of convoluted regexes. I tend to think that they do more harm than good when thet become to complex to understand in less than three seconds.
Finally i tried a simple validation and works good :-(
function validate(){
var str = document.getElementById('percentage').value;
if(isNaN(str))
{
//alert("value out of range or too much decimal");
}
else if(str > 100)
{
//alert("value exceeded");
}
else if(str < 0){
//alert("value not valid");
}
}

Resources