Getting the file size in c++ - c++

I have a file and I want to get the size of the file. I can use only _wfopen or _wfopen_s for opening the file because my file path type is std::wstring.
FILE* p_file = NULL;
p_file=_wfopen(tempFileName.c_str(),L"r");
fseek(p_file,0,SEEK_END);
but I am getting an error
error C2220: warning treated as error - no 'object' file generated

To get rid of your error message, you need to fix the issue that is generating warning.
If you compile this code:
#include "stdafx.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
FILE* p_file = NULL;
std::wstring tempFileName = L"c:\\test.txt";
p_file=_wfopen(tempFileName.c_str(),L"r");
if(!p_file)
{
perror("Open failed.");
return 0;
}
fseek(p_file,0,SEEK_END);
fclose(p_file);
return 0;
}
You will get this warning:
warning C4996: '_wfopen': This function or variable may be unsafe. Consider using _wfopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
So, listen what it says, and do the following:
#include "stdafx.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
FILE* p_file = NULL;
std::wstring tempFileName = L"c:\\test.txt";
_wfopen_s(&p_file, tempFileName.c_str(),L"r");
if(!p_file)
{
perror("Open failed.");
return 0;
}
fseek(p_file,0,SEEK_END);
fclose(p_file);
return 0;
}
There is a way to turn off this warning by putting _CRT_SECURE_NO_WARNINGS in Project Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions, but you should always prefer safe alternatives to these functions.
Also, before fseek you should check if your p_file pointer is NULL.

Related

How to share a directory using C++ so everyone can access

I'm trying to make a program so that when it run, it will create a new folder on C://. I also want to add a feature where the folder can have a shared permission to everyone. So, everyone can access and read/write
I've tried using netshareadd but I always got a compiler warning, how do I get rid of it?
This is creating new directory code :
#include <direct.h>
int main()
{
mkdir("c:/scan");
return 0;
}
This is the netshareadd code :
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <stdio.h>
#include <lm.h>
#pragma comment(lib, "Netapi32.lib")
void wmain( int argc, TCHAR *argv[ ])
{
NET_API_STATUS res;
SHARE_INFO_2 p;
DWORD parm_err = 0;
if(argc<2)
printf("Usage: NetShareAdd server\n");
else
{
//
// Fill in the SHARE_INFO_2 structure.
//
p.shi2_netname = TEXT("TESTSHARE");
p.shi2_type = STYPE_DISKTREE; // disk drive
p.shi2_remark = TEXT("TESTSHARE to test NetShareAdd");
p.shi2_permissions = 0;
p.shi2_max_uses = 4;
p.shi2_current_uses = 0;
p.shi2_path = TEXT("C:\\scan");
p.shi2_passwd = NULL; // no password
//
// Call the NetShareAdd function,
// specifying level 2.
//
res=NetShareAdd(argv[1], 2, (LPBYTE) &p, &parm_err);
//
// If the call succeeds, inform the user.
//
if(res==0)
printf("Share created.\n");
// Otherwise, print an error,
// and identify the parameter in error.
//
else
printf("Error: %u\tparmerr=%u\n", res, parm_err);
}
return;
}
22 22 D:\kerja\NETSHARE.cpp [Warning] deprecated conversion from
string constant to 'LPWSTR {aka wchar_t*}' [-Wwrite-strings]
This is the warning that I always got when compiling the netshareadd code
NetShareAdd requires a non const parameter. Some Windows APIs modify the passed buffer (or are way old) so you need a wchar_t*, not a const wchar_t* which is what a L"string" produces.
Solution, copy the const wchar_t* into a vector and pass the vector's data() member to the function (don't forget the null terminator).

Geting the file size of a system application on windows in C++

I am trying to get the file size of a system application on windows. To test this i have created a test application that tries to get the file size of smss.exe in C:\Windows\System32\smss.exe but it fails with error: ERROR_FILE_NOT_FOUND. The file does actually exist (i have checked). I've also tried different methods for getting the file size, with: FindFirstFile, CreateFile and GetFileSizeEx. But all return the same error. I would also like to read the file contents.
What am i doing wrong?
The code:
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
__int64 getFileSize(LPWSTR filePath)
{
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesEx(filePath, GetFileExInfoStandard, &fad))
{
_tprintf(TEXT("\n CAnt get file size for file %s error %d"), filePath, GetLastError());
return 0;
}
LARGE_INTEGER size;
size.HighPart = fad.nFileSizeHigh;
size.LowPart = fad.nFileSizeLow;
return size.QuadPart;
}
int _tmain(int argc, _TCHAR* argv[])
{
_tprintf(TEXT("File size %d "), getFileSize(L"C:\\Windows\\System32\\smss.exe"));
}
As your application is 32-bit, the system redirects your path to go to SysWOW64 instead, where there is no smss.exe. While you have discovered that Wow64DisableWow64FsRedirection disables this redirection, also consider that having a 64-bit program would also do the trick.
Getting the size of a file is already answered here (can't yet add a comment to your question, so I need to write it as an answer):
How can I get a file's size in C++?
std::ifstream::pos_type filesize(const char* filename)
{
std::ifstream in(filename, std::ifstream::in | std::ifstream::binary);
in.seekg(0, std::ifstream::end);
return in.tellg();
}

Pantheios write to extenal file

I looked around and I couldn't find the answer to how exactly to do this. I am trying to use Pantheios for logging and I want to write to an external file (otherwise whats the point). I am following one of the examples provided but It doesn't seem to be making the log file anywhere. Here is the code:
Edit: Also pantheios_be_file_setFilePath is returning -4 (PANTHEIOS_INIT_RC_UNSPECIFIED_FAILURE) so thats.....not helpful
#include "stdafx.h"
#include <pantheios/pantheios.hpp>
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.WindowsConsole.h>
#include <pantheios/implicit_link/be.file.h>
#include <pantheios/frontends/fe.simple.h>
#include <pantheios/backends/bec.file.h>
#include <pantheios/inserters/args.hpp>
PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("LogTest");
int _tmain(int argc, _TCHAR* argv[])
{
try
{
pantheios_be_file_setFilePath(PANTHEIOS_LITERAL_STRING("testlogforme.log"), PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BEID_ALL);
pantheios::log(pantheios::debug, "Entering main(", pantheios::args(argc,argv, pantheios::args::arg0FileOnly), ")");
pantheios::log_DEBUG("debug yo");
pantheios::log_INFORMATIONAL("informational fyi");
pantheios::log_NOTICE("notice me!");
pantheios::log_WARNING("warning!!");
pantheios::log_ERROR("error omg");
pantheios::log_CRITICAL("critical!!!");
pantheios::log_ALERT("alert mang");
pantheios::log_EMERGENCY("EMERGENCY!!!!!");
pantheios_be_file_setFilePath(NULL, PANTHEIOS_BEID_ALL);
system("pause");
return EXIT_SUCCESS;
}
catch(std::bad_alloc&)
{
pantheios::log_ALERT("out of memory");
}
catch(std::exception& x)
{
pantheios::log_CRITICAL("Exception: ", x);
}
catch(...)
{
pantheios::puts(pantheios::emergency, "Unexpected unknown error");
}
return EXIT_FAILURE;
}
Maybe I'm not calling a method or maybe its not being saved to a good location?
It turns out that some of the examples out there for pantheios are incorrect. You DO need to call pantheios_init() even if you are in C++. Here Is the example I got to work after deleting all my code and implementing an example that works.
// Headers for main()
#include <pantheios/pantheios.hpp>
#include <pantheios/backends/bec.file.h>
// Headers for implicit linking
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.file.h>
PANTHEIOS_EXTERN_C const char PANTHEIOS_FE_PROCESS_IDENTITY[] = "testLOL";
int main()
{
if(pantheios::pantheios_init() < 0)
{
return 1;
}
pantheios::log_NOTICE("log-1"); // save until log file set
pantheios_be_file_setFilePath("mylogfile.log"); // sets log file; write "log-1" stmt
pantheios::log_NOTICE("log-2"); // write "log-2" stmt
pantheios_be_file_setFilePath(NULL); // close "mylogfile"
pantheios::log_NOTICE("log-3"); // save until log file set
pantheios_be_file_setFilePath("mylogfile2.log"); // sets log file; write "log-3" stmt
pantheios::log_NOTICE("log-4"); // write "log-4" stmt
//system("pause");
return 0;
} // closes "mylogfile2" during program closedown
I found the example on a different post on stack overflow but like I said, the built in examples do not work.

C++: some errors about const char* and printf

I found this code for reading data from my USB peripheral:
#include "stdafx.h"
#define IWEARDRV_EXPLICIT
#include <windows.h>
#include <iweardrv.h>
int _tmain(int argc, _TCHAR* argv[])
{
// Load functions dynamically (in case they don't have a VR920)
HINSTANCE iweardll = LoadLibraryA("iweardrv.dll");
if (!iweardll) {
printf("VR920 drivers are not installed, you probably don't have a VR920.");
return 2;
}
IWROpenTracker = (PIWROPENTRACKER) GetProcAddress(iweardll, "IWROpenTracker");
IWRCloseTracker = (PIWRCLOSETRACKER) GetProcAddress(iweardll, "IWRCloseTracker");
IWRZeroSet = (PIWRZEROSET) GetProcAddress(iweardll, "IWRZeroSet");
IWRGetTracking = (PIWRGETTRACKING) GetProcAddress(iweardll, "IWRGetTracking");
IWRGetVersion = (PIWRGETVERSION) GetProcAddress(iweardll, "IWRGetVersion");
// Try to connect to the VR920 tracker
if (IWROpenTracker()) {
printf("VR920 is not connected.");
return 1;
}
// Read 20 samples
for (int i=1; i<=20; i++) {
LONG y, p, r;
double yaw, pitch, roll;
if (!IWRGetTracking(&y,&p,&r)) {
yaw = y*(180.0/32768.0);
pitch = p*(180.0/32768.0);
roll = r*(180.0/32768.0);
printf("Yaw=%lf degrees, Pitch=%lf degrees, Roll=%lf degrees", yaw, pitch, roll);
} else {
printf("Unable to read tracking.");
}
Sleep(500);
}
// Tidy up
IWRCloseTracker();
FreeLibrary(iweardll);
return 0;
}
Where I've setted additional include directory for include file iweardrv.h. It returns me these errors:
IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR"
IntelliSense: identifier "printf" is undefined
How do I avoid the errors? First error refers to LoadLibrary argument "iweardrv.dll" (a dynamic Library related to iweardrv.h) and second error refers to all printf calling lines.
EDIT: I corrected the first error using LoadLibraryA() because it takes a const char* but I cannot correct the second error.
The first error is because you are compiling with UNICODE defined and LoadLibrary expects a wide string. Use the L prefix to specify a wide literal:
LoadLibrary(L"iweardrv.dll");
The second error is due to a missing #include. You need to include stdio.h to define printf:
#include <stdio.h>
For C++ it would be more normal to use std::cout rather than printf.

C++ Application That Uses MSI Automation API 32 and 64bit

I am trying to create simple c++ win32 console app(in vs2010) that calls windows installer automation api. But I am failing so far. This approach causes the "Microsoft C++ exception: _com_error at memory location" error.
How to correctly use this api? How to make it work correctly on 32 and 64 bit system with only one .exe file?
Many thanks,
Marek
#include "stdafx.h"
#include <windows.h>
#include <atlstr.h>
#import "msi.dll"
using namespace WindowsInstaller;
_bstr_t GetInstalledProduct(InstallerPtr pInstaller,_bstr_t upgradeCode){
StringListPtr installedProducts = pInstaller->GetRelatedProducts(upgradeCode);
return installedProducts->Count > 0 ? installedProducts->GetItem(0) : "";
}
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
InstallerPtr pInstaller("WindowsInstaller.Installer");
_bstr_t upgradeCode("4C34BD16-CAD4-4059-B074-777793406C5F");
_bstr_t installedProduct = GetInstalledProduct(pInstaller, upgradeCode);
StringListPtr features = pInstaller->GetFeatures(installedProduct);
::CoUninitialize();
return 0;
}
I finally found the solution. The correct way is include msi.lib in linker includes and use Msi.h from windows sdk.
#include "stdafx.h"
#include <windows.h>
#include <Msi.h>
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t productCode[255];
int result = MsiEnumRelatedProducts(L"{4C34BD16-CAD4-4059-A074-777493406C5F}", 0, 0, productCode);
wchar_t featureName[255];
wchar_t featureParent[255];
MsiEnumFeatures(productCode, 0, featureName, featureParent);
INSTALLSTATE featureState = MsiQueryFeatureState(productCode, L"FeatureName");
return 0;
}