converting source code from window to linux - c++

c++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
I am converting some source code from windows to running on ubuntu.
However, the windows is using the code below to log messages and get the current time the message is logged. However, this is windows. What is the best way to convert this to running on linux?
struct _timeb timebuffer;
char *timeline;
_ftime(&timebuffer);
timeline = ctime(&(timebuffer.time));
Many thanks for any advice,

in linux a similar function ftime is used which gives you the time do
#include <sys/timeb.h>
/* .... */
struct timeb tp;
ftime(&tp);
printf("time = %ld.%d\n",tp.time,tp.millitm);
this will give you the time in second and milliseconds.

The windows code is calling ctime, which is available on Linux too and prepares a date-time string such as:
"Wed Jun 30 21:49:08 1993\n"
The man page for ctime() on Linux documents:
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
So, you don't want to use ftime() on linux... that populates a struct timeb buffer which isn't accepted by ctime().
Instead, you can get/use a time_t value using the time() function as in:
#include <time.h>
time_t my_time_t;
time(&my_time_t);
if (my_time_t == -1)
// error...
char buffer[26]; // yes - a magic number - see the man page
if (ctime_r(&my_time_t, buffer) == NULL)
// error...
// textual representation of current date/time in buffer...

Use Boost libraries (datetime) as your questions look to be more about date/time. Most of the boost lib is portable. If you look for GUI libraries QT is the best one which is again portable b/w windows/*nix.

Related

How can I get the real size of a file with C++?

I'm using tellg() to get the size of some files, and it's very important for this project get the real/correct size of files. Now I'm bit worried because a read that tellg() doesn't work perfectly but it can get the wrong size, maybe bigger than the real size. For example here: tellg() function give wrong size of file?
How can I get the correct size?? or isn't it true that tellg does'nt work very well?
This is my code with tellg():
streampos begin,end;
ifstream file_if(cpd_file, ios::binary);
begin = file_if.tellg();
file_if.seekg(0, ios::end);
end = file_if.tellg();
file_if.close();
size = end - begin;
To get file's size and other info like it's creation and modification time, it's owner, permissions etc. you can use the stat() function.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat s;
if (stat("path/to/file.txt", &s)) {
// error
}
printf("filesize in bytes: %u\n", s.st_size);
Documentation:
Linux version: stat(2)
Windows version: _stat, _stat32, _stat64, _stati64, _stat32i64, _stat64i32, _wstat, _wstat32, _wstat64, _wstati64, _wstat32i64, _wstat64i32
At this moment, you can use boost::filesystem::file_size to get the file size.
In the near future, it will be standardized to std::filesystem::file_size, it's an experimental feature, see std::experimental::filesystem::file_size.
std::experimental::filesystem::file_size is supported by:
MSVC 2013 or later,
libstdc++ 5.3 or later
libc++ 3.8 or later

How to get timezone abbreviation under Windows

We are trying to get the timezone from std::tm with strftime:
char timezone[50];
strftime(timezone, sizeof(timezone), "%Z", &timeCreated);
On iOS, we get "EST" which is what we want. But on Windows, we get "Eastern Summer Time". Anybody know how to consistently get the current timezone in C++ in abbreviation form?
I consider making the abbreviation from the full name of the timezone by simply picking out the first character in each word. But I check the list of abbreviations and notice that we could have timezone like this one "Chuuk Time" and abbreviated as "CHUT". Which makes manually adjusting not possible.
Not the same as Question: Windows Timezone and their abbreviations? I don't need a full list of all timezones and abbreviations. But instead, I need a systematic way to the current timezone using for example strftime. I want them to use the system's current timezone and the the current local.
Using this free, open-source library that has been ported to VS-2013 and later:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
using namespace date;
std::cout << format("%Z\n", make_zoned(current_zone(), system_clock::now()));
}
This just output for me:
EDT
Fully documented.
This library uses the IANA timezone database, and when current_zone() is called, translates the current Windows timezone into the appropriate IANA timezone.
Time zone information under Windows is kept in registry, you can find it in the following registry key:
HKEY_LOCAL_MACHINE
SOFTWARE
Microsoft
Windows NT
CurrentVersion
Time Zones
time_zone_name
you will not find there any abbreviations. The reason is mostly because it is not standardised, and also one abbreviation can be assigned to many time zone names, for more read here. Your aproach with taking first letter is fine, you can look up names also on this wiki:
https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
Also see this thread from MSDN forums:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/3aa4420a-a5bf-48a3-af13-17a0905ce366/is-there-any-way-to-get-timezone-abbreviations?forum=csharpgeneral
GetDynamicTimeZoneInformation is probably a good choice. However, the minimum supported versions are Windows Vista, Windows Server 2008 and Windows Phone 8. So for anything below that GetTimeZoneInformation is better.
However another issue is both sometimes return StandardName or DaylightName empty.
In that case you have to use the windows registry as marcinj has stated. Here is the function taken from gnu cash which was also modified from glib.
static std::string
windows_default_tzname(void)
{
const char *subkey =
"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
constexpr size_t keysize{128};
HKEY key;
char key_name[keysize]{};
unsigned long tz_keysize = keysize;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, subkey, 0,
KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
{
if (RegQueryValueExA(key, "TimeZoneKeyName", nullptr, nullptr,
(LPBYTE)key_name, &tz_keysize) != ERROR_SUCCESS)
{
memset(key_name, 0, tz_keysize);
}
RegCloseKey(key);
}
return std::string(key_name);
}
This can be done with the Windows Runtime (WinRT) API, specifically the Calendar.GetTimeZone method. I don't have the C++ code to do so, but here it is with Rust/WinRT version 0.7 from the Rust crate iana-time-zone. The C++ version will be similar.
use windows::globalization::Calendar;
let cal = Calendar::new()?;
let tz_hstring = cal.get_time_zone()?;
# convert the Windows HString to a Rust std::string::String
tz_hstring.to_string()

Converting UNIX timestamp using ctime

I have a unix time stamp as follows
char timestamp[100];
strcpy(timestamp,"701729943");
time_t timeval=ctime(timestamp);
printf("Time %s",timeval);
If the check the value of the timestamp in the online unix time convertor it shows 27th march 1992, but if the check the program's output it shows feb 25,1996. How to rectify this?
You're using ctime the wrong way around: it expects a pointer to a time_t and returns a string, whereas you're passing it a string and expect it to return a time_t. Does your compiler not warn you about that?
Anyway, it is meant to be used this way:
time_t timeval = 701729943;
printf("Time %s", ctime(&timeval));
If you only have the UNIX timestamp as a string, use strtoul or atoi to so to make a time_t from it, then do this.

Get Current Time in mm/dd/yyyy in C++

I am using the following code for setting the time in a Date Control in MFC using C++
CTime date;
date = date.GetCurrentTime();
this->m_headerDate.SetTime(&date);
This will get the Date and set it to the control in what ever format the user machine uses. But I want to set it to a format of ONLY mm/dd/yyyy.
There should be some way of doing this in MFC. Are there any utility functions for this?
Thanks,
Without MFC:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
const int MAXLEN = 80;
char s[MAXLEN];
time_t t = time(0);
strftime(s, MAXLEN, "%m/%d/%Y", localtime(&t));
std::cout << s << '\n';
}
Compiled Code
With MFC:
This function formats a date as a date string for a specified locale. The function formats either a specified date or the local system date.
int GetDateFormat(
LCID Locale,
DWORD dwFlags,
CONST SYSTEMTIME* lpDate,
LPCTSTR lpFormat,
LPTSTR lpDateStr,
int cchDate
);
change LPCTSTR lpFormat to MM:dd:yyyy
If you're talking about getting a specific textual representation of a date/time, you can use strftime() to format a date in many different ways, including the one specified in your question.
You will need a variable of type time_t using the facilities in the ctime header. So you can either switch to using those times, or I believe CTime::GetTime( ) will give you one.
However, if you're talking about forcing a control to display it's date/time in a specific format, that's a property of the control itself. For example, CDateTimeCtrl provides a SetFormat() method which will modify how it displays its data.
Here I'm storing value in a CString variable
Try this code:
CString strTime;
CTime date;
date = GetCurrentTime();
strTime = date.Format(_T("%m/%d/%Y"));
I have found a way of doing this...not sure if this is the simplest way though
Since we already have a datetime control .All we can do is just use the Setformat Function of the DatetimeControl. PFB an example of this
CDateTimeCtrl m_DateTimeCtrl;
m_DateTimeCtrl.SetFormat(_T("MM/dd/yyyy"));
The above will set it up to the format of 01/14/2015 which is desired. Thanks to Paxdiablo, Himanshu and Irrational Person for the inputs. They did point me in right direction with different options.

How can I determine a file's creation date in Windows?

How can I get the date of when a file was created? I am running Windows.
On Windows, you should use the GetFileAttributesEx function for that.
For C, it depends on which operating system you are coding for. Files are a system dependent concept.
If you're system has it, you can go with the stat() (and friends) function: http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html.
On Windows you may use the GetFileTime() function: http://msdn.microsoft.com/en-us/library/ms724320%28v=vs.85%29.aspx.
Unix systems don't store the time of file creation. Unix systems do store the last time the file was read (if atime is turned on for that specific file system; sometimes it is disabled for speed), the last time the file was modified (mtime), and the last time the file's metadata changed (ctime).
See the stat(2) manpage for details on using it.
Use stat function
see here
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
struct tm* clock; // create a time structure
struct stat attrib; // create a file attribute structure
stat("afile.txt", &attrib); // get the attributes of afile.txt
clock = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure