Quantcast
Channel: Visual C forum
Viewing all 15302 articles
Browse latest View live

How to add scroll bar for a docking pane in MFC Feature Pack!

$
0
0

HI,

I created a docking pane by modifying a previous dialog but i am not able to add a scroll bar to the docking pane. I selected the vertical scroll bar = true option in the properties too.  Would be really helpfull if someone can explain how to do so.

Thanks,




[VS2013] Hierarcy projects in solution + project headers only + linker

$
0
0
Hello my friend %User%! Please help me!

In order to separate a sense components, I have allocated some headers in one projects without cpp-files.
In compile time will appear a warning like:
warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library

How is more correctly to write a stub to remove warning? (without linker /ignore:4221)


At the next case I have some projects which are connected at one solution with references.
And in compile time appears error like a:
error LNK2019: unresolved external symbol __imp__wglCreateContext@4 referenced in function _main
error LNK1120: 1 unresolved externals

It seems like a linker doesn't find some lib references from child projects.


Then I'm trying to use:
Link Library Dependencies<- http://msdn.microsoft.com/en-us/library/024awkd1.aspx
at each project properties in projects references.

It looks like everything was compiled... But again appears some warnings:
11>Windows.GDI.lib(GDI32.dll) : warning LNK4006: __NULL_IMPORT_DESCRIPTOR already defined in Unknown.OpenGL.lib(OPENGL32.dll); second definition ignored
11>Windows.GDI.lib(GDI32.dll) : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: __IMPORT_DESCRIPTOR_GDI32 already defined in Windows.GDI.lib(GDI32.dll); second definition ignored
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: __NULL_IMPORT_DESCRIPTOR already defined in Unknown.OpenGL.lib(OPENGL32.dll); second definition ignored
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: GDI32_NULL_THUNK_DATA already defined in Windows.GDI.lib(GDI32.dll); second definition ignored
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: _AbortDoc@4 already defined in Windows.GDI.lib(GDI32.dll); second definition ignored
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: __imp__AbortDoc@4 already defined in Windows.GDI.lib(GDI32.dll); second definition ignored
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: _AbortPath@4 already defined in Windows.GDI.lib(GDI32.dll); second definition ignored
11>Windows.Kernel.lib(GDI32.dll) : warning LNK4006: __imp__AbortPath@4 already defined in Windows.GDI.lib(GDI32.dll); second definition ignored
+ some warnings from empty cpp projects

Windows.Kernel and Windows.GDI - projects (static libraries) without cpp

How to fix this?


I think the problem is multiple cross-references in one static library (gdi.lib or opengl32.lib)

At the project properties I'm found an option:
Use Library Dependency Inputs<- http://msdn.microsoft.com/en-us/library/024awkd1.aspx

Let's try... All errors disappear but we have this first problem with the main project which can't find any references of lib's from child projects
error LNK2019: unresolved external symbol __imp__wglCreateContext@4 referenced in function _main
error LNK1120: 1 unresolved externals

I also tried to change Link Library Dependencies and Use Library Dependency Inputs at the Linker properties - nothing.

If you fprcing link the lib in the main project (OpenGL32.lib) or try to writw anpragma comment lib, it works. But it's not a solution, because the main project doesn't use OpenGL directly. It would be great if the main project could get all the stuff from child project and linked correctly.

What to do in this situation?

std::getline and wfstream

$
0
0
std::wfstream f;
f.open( L"file.txt", std::ios::in); //error: no matching function for call to 'std::basic_fstream<wchar_t>::open(const wchar_t*, std::ios_base::openmode&)'

My compiler is giving me an error when reading this line, can anyone spot what I am dong wrong?

Thanks in advance.

Empty Project Entry Point in MSVC++ 2010

$
0
0

I am starting with an empty project in VC++ 2010. How am I going to get to an entry point. Where is Main.cpp? What input files is it expecting for "int main". I do not see where to configure input files in the Project Configuration. Where is the documentation on Empty Projects?

I prefer empty projects because there is less overhead in execution.

I use a known put method of class std::fstream could not write to file

$
0
0

Program does not report any error, but the file without making any changes. Here is the code:

#include <STDIO.H> #include <IOSTREAM> #include <FSTREAM> using namespace std; int main() { //file stream fstream f; //read a char char c; //to lower int operation=1; f.open("C:\\YJ_OCX_Log\\test.txt");

if(!f.good())
printf("some error!");

while(!f.eof()) { f.get(c); if(c>='A'&&c<='Z') { if(operation) { c+=32; f.putback(c); f.put(c); } } else if(c>='a'&&c<='z') { if(!operation) { c-=32; f.putback(c); f.put(c); } } } f.flush(); f.close(); system("pause"); return 0; }

Where is problem? What's the solution? Thanks.

妆台秋思



Need to adjust the lines

$
0
0

Hi,
I want to have text output file instead. what to adjust below?

    std::ofstream ostrm2("c:\\flout.ord", std::ios::binary | std::ios::out );
	if (ostrm2.is_open())
	{
		for (size_t i = 0; i < records.size(); i++)
		{
			ostrm2.write((char*)&records[i], sizeof(nameval));
			...


Many Thanks & Best Regards, Hua Min

DeleteFile()/MoveFileEx() returning access denied

$
0
0

As part of an MSI uninstall custom action I'm cleaning up some files under the AppData\LocalLow\<ProductFolder>. While deleting our directory I'm calling RemoveDirectory() and DeleteFile() and checking for success. If the function fails I use GetLastError and check that against ACCESS_DENIED (5). If 5 is the error than I use MoveFileEx() with the delay until reboot flag. When I testing this I'm seeing that MoveFileEx is also returning 5 and that the PendingFileRenames registry value is not being set.

I'm seeing this issue on Windows 7 and I'm running the action as a Deferred Execution in System Context. Any ideas on why MoveFileEx is not working like it does on pre-UAC systems? I've put a copy of my relevant code below:

 

 

if(!DeleteFile(szFileName)) 
{// delete the file failed
	dw = GetLastError();
	//if we can't delete the file because something has a lock on it then
	//mark it to delete on reboot and let the installer know to reboot
	if( ERROR_ACCESS_DENIED == dw )
	{
		_stprintf_s(msgBuffer, MAX_PATH * 2, 	_T("Failed to delete file %s, file access is denied"), szFileName);
		LogMsg(msgBuffer);
		if( !MoveFileEx(szFileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) ) //<<<---returns ACCESS_DENIED a 2nd time
		{
			dw = GetLastError();_stprintf_s(msgBuffer, MAX_PATH * 2, _T("ERROR: %d - Failed to mark %s as delete on reboot"), dw, szFileName);
			LogMsg(msgBuffer);

		}//end if
		else
		{
			_stprintf_s(msgBuffer, MAX_PATH * 2, 
				_T("The file %s is marked to delete on reboot"), szFileName);
			LogMsg(msgBuffer);
			//let the install know to reboot at the end
			MsiSetProperty(hMSI, _T("ISSCHEDULEREBOOT"), _T("1"));

		}//end else

	}//end if

}//end if

 

 


Deadlock in RtlReAllocateHeap?

$
0
0

Did anyone experienced deadlocks with a following stack trace:

The code is executed in multiple processes (~24-40 processes) on a machine with many cores and RAM. During execution the machine is loaded but there are still spare CPU cores availabel and enough memory. Periodically, all of them get stucked and I see the following stack trace in the process explorer app. When the same code is executed in a smaller number of processes (< 8) or on developer's desktop with one CPU/4 Cores the issue does not seem to appear. The OS is Windows 2008 R2. 

Can an application code cause this problem or this is something Windows related? What tools might be used to diagnose the issue?


Please mark replies as answers if they help


Extract helpstring from enum member

$
0
0

I have an enumeration defined in idl:

typedef enum
{
 [helpstring("My help string")]
 MyValue = 231,

} MyENUM;

The TypeLibarary is included in compiled dll as resource item. I can obtain it at runtime with LoadTypeLibEx function. Is it possible to obtain the value of the helpstring (to use for generating error message) from MyENUM for a particular member (MyValue) having an integer value 231?


Please mark replies as answers if they help



16 or 32 bit C 'time' runtime library output differs

$
0
0
Hello developers,
 
I have a legacy 16 bit application written in C which outputs the system time in UTC format (Unix epoch time).
 
The following is the code snippet:
time_t  t ;
printf("%ld\n", time(&t)) ;
 
There is a difference between the time displayed in seconds on 16 bit and 32 bit application built with 16 bit and 32 bit Microsoft CL compiler for the above code.
 
Can anyone explain why the difference occurs?
 
For example here is the sample executed at the same time,
32 bit:1404391074
16 bit:1404436063
 
Thanks,
Vishnu

MDI Feature Pack Tab display speed

$
0
0

With the same logic, when I switch between old MDI and tab display, I observe a major speed performance.  In my sample test program, I created 25, 50, 75, &100 MDI windows.  As more MDI windows are created, the speed drop significantly.

FYI: My computer is I7 (3.4Ghz) with 24GB memory

Here is my statistic:

- 25 MDI windows, old MDI 0 seconds, tab 2 seconds

- 50 MDI windows, old MDI 1 seconds, tab 12 seconds

- 75 MDI windows, old MDI 1 seconds, tab 18 seconds

- 100 MDI windows, old MDI 1 seconds, tab 25 seconds

Having trouble rotating an IWICBitmap

$
0
0

I have read every resource I can find, and cannot make this work. I can read an image file into an IWICBitmap, convert it to an ID2D1Bitmap, and view it, all day long. But what I want to do is rotate the IWICBitmap 180 degrees, and store it back on disk. This is eluding me. Here is some code that reads an image from a file, and this works completely fine:

IWICFormatConverter* pWICConv = NULL; IWICBitmapDecoder* pWICDecoder = NULL; IWICBitmapFrameDecode* pWICBmpSrc = NULL; //Create a decoder. HRESULT hr = mpWICFactory->CreateDecoderFromFilename( (LPCWSTR)FullPath, NULL, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &pWICDecoder); //Retrieve frame '0' and put it in pWICBmpSrc. if (SUCCEEDED(hr)) hr = pWICDecoder->GetFrame(0, &pWICBmpSrc); /*Create a format converter using the IWICImagingFactory to convert the image data from one pixel format to another, etc.*/ if (SUCCEEDED(hr)) hr = mpWICFactory->CreateFormatConverter(&pWICConv); /*Initialize the format converter with all sorts of information, including the frame that was decoded above.*/ if(SUCCEEDED(hr)) hr = pWICConv->Initialize(pWICBmpSrc, mPixelFormatWIC, WICBitmapDitherTypeNone, NULL, 0.f, WICBitmapPaletteTypeMedianCut); //Create the WICBitmap (mpImgWIC) from the Bitmap source hr = mpWICFactory->CreateBitmapFromSource( pWICConv, WICBitmapCacheOnLoad,&mpImgWIC);

The code above works great.  I can load images using IWICBitmap all day long, convert them to ID2D1Bitmaps, and view them, no problem.  But I here is the EXACT same code with a quick section inserted to rotate the IWICBitmap by 180 degrees.

IWICFormatConverter* pWICConv = NULL;
IWICBitmapDecoder* pWICDecoder = NULL;
IWICBitmapFrameDecode* pWICBmpSrc = NULL;

//Create a decoder.
HRESULT hr = mpWICFactory->CreateDecoderFromFilename(
                      (LPCWSTR)FullPath, 
                       NULL, 
                       GENERIC_READ, 
                       WICDecodeMetadataCacheOnLoad, &pWICDecoder);

//Retrieve frame '0' and put it in pWICBmpSrc.
if (SUCCEEDED(hr))
  hr = pWICDecoder->GetFrame(0, &pWICBmpSrc);

/*Create a format converter using the IWICImagingFactory to convert the image data from one pixel format to another, etc.*/
if (SUCCEEDED(hr))
  hr = mpWICFactory->CreateFormatConverter(&pWICConv);

/*Initialize the format converter with all sorts of information, including the frame that was decoded above.*/
if(SUCCEEDED(hr))
  hr = pWICConv->Initialize(pWICBmpSrc,
                            mPixelFormatWIC,
			    WICBitmapDitherTypeNone,
                            NULL,
                            0.f,
  		            WICBitmapPaletteTypeMedianCut);


///////////////////////////////////////////////////
/*This new section fails to do anything, but hr comes back
S_OK in both instances*/
IWICBitmapFlipRotator *FlipRotator = NULL;
if (SUCCEEDED(hr))
  hr = mpWICFactory->CreateBitmapFlipRotator(&FlipRotator);
if (SUCCEEDED(hr))
  hr = FlipRotator->Initialize(pWICConv, 
                             WICBitmapTransformRotate180);
///////////////////////////////////////////////////



//Create the WICBitmap (mpImgWIC) from the Bitmap source 
hr = mpWICFactory->CreateBitmapFromSource(
                       pWICConv,
                       WICBitmapCacheOnLoad,&mpImgWIC);

Can anyone tell me what I'm doing wrong?

Thanks!

Winsock: client recv produces 10053 when server's listen sock is non-blocking (blocking works - whyever)

$
0
0

I have a Server and a Client Application, both on the same System.

The client connects to the system via a TCP-Socket, which works fine.
The Server has a loop in which it keeps accepting clients on a non-blocking listen socket.

The function body for the accepting loop:

     
std::unique_ptr<Connection> p_conn(nullptr);
    		bool connection_establish_pending = false;
    		while(!StopCondition_)
    		{
    			if(!connection_establish_pending)
    				p_conn.reset(new Connection);
    			// accept new connection
    			auto stat = p_conn->Accept(ListenSocket_);
    			if(stat == Connection::Error)
    				break;	// listen socket is unusable
    			if(stat  == Connection::Wouldblock)
    			{
    				connection_establish_pending = true;
    				std::this_thread::sleep_for(std::chrono::milliseconds(300));
    				continue;
    			}
    			// connection has been established
    			connection_establish_pending = false;
    			// create client handling thread
    			std::thread t(_connection_handler_thread, p_conn.release(), this);
    			this->ThreadList_.push_back(std::move(t));	// add to list
    		}



`Connection` is a simple wrapper around a socket.
After the connection was accepted a new thread is started to handle communications with the client:

void ConnectionHandler(std::unique_ptr<Connection> pConn)
    {
    	Message msg;
    	std::vector<char> buf;
    	try
    	{
    		// main loop
    		while(pConn->Recv(msg))		// receive a message
    		{
    			switch(msg.RequestCode())
    			{
    			case 1:
    				{
    					// prepare answer msg...
    					pConn->Send(msg);
    				}
    				break;
    			case 2:
    				// ...
    			}
    		} // while(recv)
    	}
    	catch(...)
    	{
    	}
    }




At the moment, the client is nothing more than the following:

  std::string ip = "localhost", port = "12345";

            // Connect to server
            cout << "Establishing connection..." << endl;;
            Server.Connect(ip, port);
            cout << "Connection established to: " << ip << ":" << port << endl;

            /* Send a message to host*/
            const char Data[] = "Counter"; const size_t data_size = strlen(Data);
            cout << "Sending Message \"" << Data << "\"" << endl;
            auto ret = Server.SendRequest(1, Data, data_size);
            if(!ret)
                cout << "Connection closed serverside" << endl;
            else
            {
                if(!Server.RecvAnswer(rq, vecData))
                    cout << "Connection closed serverside" << endl;
                else
                {
                    cout << "Answer:\n\tCode = " << rq  << "\n\tData:" << std::string(vecData.data(), vecData.size()) << endl;
                }

                // Now try to get the module info for "Counter"
                cout << "Requesting module info now... " << endl;
                ret = Server.SendRequest(2, Data, data_size);
                if(!ret)
                    cout << "Connection closed serverside" << endl;
                else
                {
                    if(!Server.RecvAnswer(rq, vecData))
                        cout << "Connection closed serverside";
                    else
                        cout << "Answer:\n\tCode = " << rq  << "\n\tData:" << std::string(vecData.data(), vecData.size()) << endl;
                }

            }
  



Following are my wrappers for receiving and sending data via a socket:

 //prepare a buffer to be used in calls to 'recv'
        std::unique_ptr<char[]> pBuf(new char[BytesToRecv]);

        int Ret = 0;
    size_t BytesReceived = 0;


    do
    {
        //clear the buffer
        memset(pBuf.get(), '\0', BytesToRecv);

        Ret = recv(Get(), pBuf.get(), BytesToRecv - BytesReceived, 0);
        if(Ret == 0)    // Graceful shutdown
            return Status::Closed;
        if (Ret == SOCKET_ERROR)
        {
            auto ret_code =  GetErrorStatus();    // Wouldblock, Disconnected/Unreachable, Aborted
            if(ret_code == Status::Error)
                throw(socket_exception(Get(), "Failed to recv"));
            return ret_code;
        }


        //Append to the Data-Buffer
        //Data.append(inc::StringToWString(std::string(pBuf.get(), Ret)));
        memcpy_s(&pData[BytesReceived], BytesToRecv - BytesReceived, pBuf.get(), Ret);


        //Count bytes received
        BytesReceived += static_cast<size_t>(Ret);


        //reset the return code
        Ret = 0;

    } while (BytesReceived < BytesToRecv);
   




And here my sending code:

size_t total = 0;                //total sent
        size_t bytesleft = DataSize;    //bytes left to be sent
        int ret = 0;

        //as long as there is data to send...
        while (total < DataSize)
        {
            //...send what's left
            ret = send(Get(), pData + total, bytesleft, 0);
            if(ret == SOCKET_ERROR)
            {
                auto ret = GetErrorStatus();    // Aborted, Wouldblock, Unreachable/Disconnected
                if(ret == Status::Error)
                    throw(socket_exception(Get(), "Failed to send"));
                return ret;
            }

            total += ret;
            bytesleft -= ret;
        }
  



And here is the code to RecvAnswer: (it makes a call to the recv-code above and extracts the data to a buffer (nothin really network related except from the call to the recv)

 bool RecvAnswer(request_type& Request, std::vector<char>& vecData)
    {
        Message Msg;
        if(!pimpl->Connection_.Recv(Msg))
            return false;

        vecData = Msg.Data();
        Request = Msg.RequestCode();

        return true;
    }

The problem that occurs is, that when i run the client without breakpoints, step-through, etc it successfully sends the first request and receives data from the server. After the second request when i call recv it returns the 10053-Error.

Funnily, when i step through the code i get the 10053-error right on the first call to recv.

Turning off firewall and antivirus software does not help.

Strange thing to me is, that it workswhen i put the listening(!) socket into blocking mode.

Any help would be greatly appreciated.

Thank You!

If required, i could also add someone to my visualstudio.com-project (if she/he as an visualstudio-account) so the full code could be read.

Dumb question about upgrading from VS2008 to VS2013 - property sheet order

$
0
0

I just upgraded to VS2013 from VS2008.  I then opened one of my old projects and of course VS2013 automatically "upgraded" it.  But, I got a bunch of warnings about things being out of order with respect to the property sheets, of which I am only a little familiar.  The errors were like this:

All user macros reported below for configuration 'Debug|Win32' are used before their definition, which can cause undesirable build results; this is not supported in this release. You can resolve this by changing the inclusion order of the consuming property sheets and making sure they come after the property sheets defining the user macros.

followed by...

MSB4211: C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets (86,5); The property "TargetPlatformIdentifier" is being set to a value for the first time, but it was already consumed at "C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120\Microsoft.Cpp.Common.props (103,5)".

However, I cannot figure out how to "change the inclusion order of the consuming property sheets".  I have searched high and low but no joy.  I can't even see where the files mentioned are part of my project.  Can you help me understand what is going on?

Thanks very much!


Cannot load symbols for mfc100.dll version 10.0.30319.01.

$
0
0

Hello everyone,

I am trying to analyze a dump from one of applications deployed in the field. In the call stack there is a call to mfc100.dll, version 10.0.30319.01, but I cannot load the symbol information for that file... the same goes for msvcr100.dll.

My debugger is properly configured; I can load the symbols for kernel32.dll, user32.dll, ntdll.dll.... So I am pretty confident that this is not a configuration issue.

Is it possible that the symbol server does not contain the symbols for theses (and other) modules?

Would do we ask? We really need to have this information. We’d be willing to download it and populate our own internal servers is required.

We are on the verge of releasing new version compiled with VS2010 sp1, will we have the same problems?

 

Best Regards

-Martin


HelloAllo

C++ Embrace, Extend, Exterminate Conspiracy

$
0
0

Hello all,

I stumbled upon an entry in Wikipedia that Microsoft uses EEE (Embrace, Extend, Extinguish) methodology in their business. First, they embrace a certain open standard and incorporate them in one of their platform. Next, Microsoft extends these open standards to somehow introduce new features. Finally, once theses extensions become the de facto standard, Microsoft uses its dominance to force developers to use their version of the standard. A good example is C++/CX. I need your opinion about this one. Will it be possible that Microsoft is slowly killing the standard ISO C++ to make way for C++/CX?

error C2665: 'CObject::operator new' : none of the 3 overloads could convert all the argument types_, but it is a constructor with no arguements

$
0
0

I am converting an old project in C++ to Visual studio 2013.  when I build I get swarms of errors like this

Error9 error C2665: 'CObject::operator new' : none of the 3 overloads could convert all the argument typesl

The line that causes this one is 

m_paOurPaths[iMovePathsIterator] = new CLinearNormalPath();

New is for a constructor that takes zero arguments so I don't know why it has trouble converting. The default, no parameter, constructor for CLinearNormanPath does exist.  There are about 60 of these errors for a plethora of different paths. 

There are also errors like this

83IntelliSense: no instance of overloaded "CLinearNormalPath::operator new" matches the argument list
            argument types are: (unsigned int, TCHAR [100], int)l:\Users\Charles\Documents\Visual Studio 2013\Projects\ChessSec2014\ChessSec2014\SetOfMovePaths.cpp7139 ChessSec2014

Any clues?

could my errors be on the wrong line?

$
0
0

I have a C++ project in Visual Studio 2013.  When I build I get a lot of errors such as

Error1 error C2664: 'BOOL AfxAssertFailedLine(LPCSTR,int)' : cannot convert argument 1 from 'wchar_t [94]' to 'LPCSTR'l:\users\charles\documents\visual studio 2013\projects\chesssec2014\chesssec2014\viewtree.cpp331 ChessSec2014

But this is what is on line 33

ASSERT(pNMHDR != NULL);

So I am wondering how this can be a argument 1  error when there are no arguments and nothing has anything to to with wchar_t or LPCSTR on this line. Could it be reporting an error on the wrong line?  If it is, is there any way to make it report stuff on the right line so I can fix it.

Alternately if this error seems possible from this line then how can I fix it?

Thanks,

Chas

Executing SQL query from C++ and store the results into matrix

$
0
0

Hi All,

I am experiencing some difficulties in executing the below query from c++ (Studio 2010) and will appreciate some assistance in a code:

while compiling I've got the warning message:

Run-Time Check Failure #3 - The variable 'sqlstatementhandle' is being used without being initialized, and I finally see displayed on the screen Message: 0052E144nSQLSTATE: 0052E94C, which is coming from the *cout* statement. I was expecting to see at least a list of prices for existing identifiers.

Thus, is there a way of getting the prices for my 3 identifiers into a matrix composed of 3 column vectors? this is an illustration, but I might have n identifiers (ISN) and will need to store the values (here ClosedPrice) into a (p by n) matrix.

Thanks in advance and regards

#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>

using namespace std;

void show_error(unsigned int handletype, const SQLHANDLE& handle){
    SQLWCHAR sqlstate[1024];
    SQLWCHAR message[1024];
    if(SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
        cout<<"Message: "<<message<<"nSQLSTATE: "<<sqlstate<<endl;
}

int main(){

    SQLHANDLE sqlenvhandle;    
    SQLHANDLE sqlconnectionhandle;
    SQLHANDLE sqlstatementhandle;
    //SQLRETURN retcode;

    if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
        goto FINISHED;

    if(SQL_SUCCESS!=SQLSetEnvAttr(sqlenvhandle,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) 
        goto FINISHED;
    
    if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
        goto FINISHED;

    SQLWCHAR retconstring[1024];
    switch(SQLDriverConnect (sqlconnectionhandle, 
                NULL, 
                (SQLWCHAR*)"DRIVER={SQL Server};SERVER=IF\\SqlExpress, 1433;DATABASE=ProjectPhd;", 
                SQL_NTS, 
                retconstring, 
                1024, 
                NULL,
                SQL_DRIVER_NOPROMPT)){
        case SQL_SUCCESS_WITH_INFO:
            show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
            break;
        case SQL_INVALID_HANDLE:
        case SQL_ERROR:
            show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
            goto FINISHED;
        default:
            break;
    }
    if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
        goto FINISHED;

    if(SQL_SUCCESS!=SQLExecDirect(sqlstatementhandle, (SQLWCHAR*)"select * from SecurityData", SQL_NTS)){
        show_error(SQL_HANDLE_STMT, sqlstatementhandle);
        goto FINISHED;
    }
    else{
        char ISN[64];
        float ClosedPrice[64];
        //int id;
        while(SQLFetch(sqlstatementhandle)==SQL_SUCCESS){
            //SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
            SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, ISN, 64, NULL);
            SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, ClosedPrice, 64, NULL);
            cout<<ISN<<" "<<ClosedPrice<<endl;
        }
    }

FINISHED:
    SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle );
    SQLDisconnect(sqlconnectionhandle);
    SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
    SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
    
}

Can I change a variable defined as static const?

$
0
0

I have a variable defined as static const CSomeClass g_SomeAttribute[] = { ... };

Can I change the values of g_SomeAttribute during run-time or am I stuck with what I have defined?

Ryan

Viewing all 15302 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>