<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893519</guid>
        <pubDate>Tue, 01 Aug 2023 10:31:36 +0000</pubDate>
        <title>Определение времени создания, модификации и открытия файла</title>
        <link>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893519</link>
        <description><![CDATA[tumanovalex: Мне хотелось бы найти кроссплатформенное решение, а не только для Windows.]]></description>
        <author>tumanovalex</author>
        <category>C/C++: Общие вопросы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893517</guid>
        <pubDate>Tue, 01 Aug 2023 10:16:02 +0000</pubDate>
        <title>Определение времени создания, модификации и открытия файла</title>
        <link>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893517</link>
        <description><![CDATA[core-i7: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=436809&view=findpost&p=3893505'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>tumanovalex &#064; <time class="tag-quote__quoted-time" datetime="2023-08-01T08:57:24+00:00">01.08.23, 08:57</time></span><div class='quote '>Хотелось бы все-таки узнать, как получить время создания файла и время его открытия на C++?</div></div><br>
Используйте функцию <strong class='tag-b'>GetFileInformationByHandle()</strong>, которая возвращает информацию в структуру &quot;BY_HANDLE_FILE_INFORMATION&quot; - в ней найдёте всё, что вам нужно <em class='tag-i'>(прототип на ассемблере fasm)</em>:<br>
<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">struct &nbsp;BY_HANDLE_FILE_INFORMATION</div><div class="code_line">&nbsp;&nbsp;dwFileAttributes &nbsp; &nbsp; dd &nbsp;0</div><div class="code_line">&nbsp;&nbsp;ftCreationTime &nbsp; &nbsp; &nbsp; FILETIME</div><div class="code_line">&nbsp;&nbsp;ftLastAccessTime &nbsp; &nbsp; FILETIME</div><div class="code_line">&nbsp;&nbsp;ftLastWriteTime &nbsp; &nbsp; &nbsp;FILETIME</div><div class="code_line">&nbsp;&nbsp;dwVolumeSerialNumber dd &nbsp;0</div><div class="code_line">&nbsp;&nbsp;nFileSizeHigh &nbsp; &nbsp; &nbsp; &nbsp;dd &nbsp;0</div><div class="code_line">&nbsp;&nbsp;nFileSizeLow &nbsp; &nbsp; &nbsp; &nbsp; dd &nbsp;0</div><div class="code_line">&nbsp;&nbsp;nNumberOfLinks &nbsp; &nbsp; &nbsp; dd &nbsp;0</div><div class="code_line">&nbsp;&nbsp;nFileIndexHigh &nbsp; &nbsp; &nbsp; dd &nbsp;0</div><div class="code_line">&nbsp;&nbsp;nFileIndexLow &nbsp; &nbsp; &nbsp; &nbsp;dd &nbsp;0</div><div class="code_line">ends</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script><br>
<br>
Как видно, бонусом сразу получаем: атрибуты, размер, кол-во ссылок, серийник тома, и время создания/записи/изменения. Время хранится в виде 8-байтного значения <em class='tag-i'>(struct FILETIME)</em>, и чтобы привести его в читабельный вид, используем <strong class='tag-b'>FileTimeToSystemTime()</strong>. В скрепке файл для тестов..<br>
<br>
<span class="b-attach" data-size="990" data-hits="233" data-attach-id="65037" data-attach-post-id="0">
			<span class="b-attach__title"></span><a class='b-attach-link' href='https://forum.sources.ru/index.php?act=Attach&amp;type=post&amp;id=0&amp;attach_id=65037' title='Скачать файл' target='_blank'>FileInfo_By_Handle.zip</a> (, : 233)
		</span><br>
<span class="b-attach" data-size="27056" data-hits="354" data-attach-id="65038" data-attach-post-id="3893517">
			<span class="b-attach__title"></span><a class='b-attach-link' href='https://forum.sources.ru/index.php?act=Attach&amp;type=post&amp;id=3893517&amp;attach_id=65038' title='Скачать файл' target='_blank'>fileTime.jpg</a> (, : 354)
		</span>]]></description>
        <author>core-i7</author>
        <category>C/C++: Общие вопросы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893505</guid>
        <pubDate>Tue, 01 Aug 2023 08:57:24 +0000</pubDate>
        <title>Определение времени создания, модификации и открытия файла</title>
        <link>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893505</link>
        <description><![CDATA[tumanovalex: Спасибо большое за решение вопроса перевода времени из UTC в локальное&#33; Сам бы я не разобрался. Решение на Си для определения времени создания нашел:<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;sys\stat.h&#62;</div><div class="code_line">#include &#60;time.h&#62;</div><div class="code_line">struct stat t_stat;</div><div class="code_line">stat(fileName, &amp;t_stat);</div><div class="code_line">struct tm* timeinfo = localtime(&amp;t_stat.st_ctime); </div><div class="code_line">printf(&quot;File time and date: %s&quot;, asctime(timeinfo));</div></ol></div></div></div></div>, а вот найти код для времени открытия файла мне не удалось. Хотелось бы все-таки узнать, как получить время создания файла и время его открытия на C++?]]></description>
        <author>tumanovalex</author>
        <category>C/C++: Общие вопросы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893493</guid>
        <pubDate>Mon, 31 Jul 2023 18:09:12 +0000</pubDate>
        <title>Определение времени создания, модификации и открытия файла</title>
        <link>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893493</link>
        <description><![CDATA[Qraizer: Никогда не нужно было, так что пришлось серьёзно покопаться в вопросе.<br>
В общем, Стандарт никак не определяет, в каком формате что там и как хранится. Он  лишь утверждает, что std::filesystem::file_time_type является альясом для std::chrono::time_point&lt;&gt;, который в свою очередь основан на std::chrono::file_clock. Что такое эти самые std::chrono::file_clock и std::filesystem::file_time_type, не специфицируется, что в общем-то и неудивительно. Единственное дополнительное требование предъявляется к last_write_time:<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <div class='quote '><span class="tag-font" data-value="Courier" style="font-family:Courier">file_time_type last_write_time(const path&amp; p);</span><br>
...<br>
The time of last data modification of <strong class='tag-b'>p</strong>, determined as if by the value of the POSIX <strong class='tag-b'>stat </strong>structure member <strong class='tag-b'>st_mtime</strong> obtained as if by POSIX <strong class='tag-b'>stat</strong>().</div></div>Ок, открываем <a class='tag-url' href='https://pubs.opengroup.org/onlinepubs/009696799/basedefs/sys/stat.h.html' target='_blank'>документацию на stat</a> и среди прочего видим, что <strong class='tag-b'>st_mtime</strong> имеет тип <strong class='tag-b'>time_t</strong> и снова отсылку к стандарту IEEE Std 1003.1-2001.<br>
Оооок, берём свежий стандарт POSIX &quot;Standard for Information Technology — Portable Operating System Interface (POSIX)&quot; (он-лайн просто так нету, PDF дают только зареганным) и там видим:<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>A.4.14 Seconds Since the Epoch</span><div class='quote '>...<br>
Implementations that implement time_t as a signed 32-bit integer will overflow in 2 038. The data size for time_t is as per the ISO C standard definition, which is implementation-defined.<br>
See also <strong class='tag-b'>Epoch</strong> (on page 17).</div></div>И наконец<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <div class='quote '>Historically, the origin of UNIX system time was referred to as ‘‘00:00:00 GMT, January 1, 1970’’. Greenwich Mean Time is actually not a term acknowledged by the international standards community; therefore, this term, ‘‘Epoch’’, is used to abbreviate the reference to the actual standard, Coordinated Universal Time.</div></div><br>
Из всего этого следует заключить, что просто так значения std::filesystem::file_time_type трактовать как некие готовые к использованию цифры не следует, их сначала надо сконвертировать к подходящий формат локального времени. Локальное время можно получить из системного через тайм-зоны, системное же из файлового можно длинно через посредство UTC и всякими там to_utc(), to_sys(), а  можно проще через clock_cast&lt;&gt;.<br>
В итоге получим что-то вроде<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;iostream&#62;</div><div class="code_line">#include &#60;chrono&#62;</div><div class="code_line">#include &#60;filesystem&#62;</div><div class="code_line">#include &#60;format&#62;</div><div class="code_line">&nbsp;</div><div class="code_line">namespace fs = std::filesystem;</div><div class="code_line">namespace chr= std::chrono;</div><div class="code_line">&nbsp;</div><div class="code_line">int main()</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp;fs::file_time_type ftime = fs::last_write_time(&quot;delMe.cpp&quot;);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp;std::cout &#60;&#60; std::format(&quot;Date: {0:%F} Time: {0:%H}:{0:%M}:{0:%S}&quot;, chr::floor&#60;chr::seconds&#62;(chr::get_tzdb().current_zone()-&#62;to_local(chr::clock_cast&#60;chr::system_clock&#62;(ftime)))) &#60;&#60; std::endl;</div><div class="code_line">}</div></ol></div></div></div></div>]]></description>
        <author>Qraizer</author>
        <category>C/C++: Общие вопросы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893421</guid>
        <pubDate>Sat, 29 Jul 2023 22:53:47 +0000</pubDate>
        <title>Определение времени создания, модификации и открытия файла</title>
        <link>https://forum.sources.ru/index.php?showtopic=436809&amp;view=findpost&amp;p=3893421</link>
        <description><![CDATA[tumanovalex: Создал файл (прикрепил) и записал в него примерное время создания и модификации:<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">14:54:37 - создание через Shift+F4 в Total Commander в Notepad++</div><div class="code_line">14:57:30 - сохранение в Notepad++</div><div class="code_line">15:00:00 - сохранение в Notepad++ после корректировки</div></ol></div></div></div></div>В Windows 10 в свойствах файла на вкладке &quot;Общие&quot;:<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">Создан: 19 июля 2023 г.. 14:54:31</div><div class="code_line">Изменен: 19 июля 2023 г.. 15:00:00</div><div class="code_line">Открыт: &nbsp; 28 июля 2023 г.. 12:34:00</div></ol></div></div></div></div><br>
В программе:<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;iostream&#62;</div><div class="code_line">#include &#60;chrono&#62;</div><div class="code_line">#include &#60;filesystem&#62;</div><div class="code_line">using namespace std;</div><div class="code_line">namespace fs = filesystem;</div><div class="code_line">int main()</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp;fs::file_time_type ftime = fs::last_write_time(&quot;D:\TestPrograms\Файл-даты создания и модификации.txt&quot;);</div><div class="code_line">&nbsp;&nbsp;cout &#60;&#60; format(&quot;Date: {0:%F} Time: {0:%T}&quot;, chrono::floor&#60;std::chrono::seconds&#62;(ftime)) &#60;&#60; endl;</div><div class="code_line">&nbsp;&nbsp;system(&quot;pause&quot;);</div><div class="code_line">&nbsp;&nbsp;return 0;</div><div class="code_line">}</div></ol></div></div></div></div>время определяется как 12:00:00 (видимо UTC), а не как локальное. У меня следующие вопросы:<br>
1. Как получить локальное время?<br>
2. Как получить время создания файла и время его открытия (как на вкладке Общие в свойствах файла в Windows).<br>
Помогите, пожалуйста, разобраться.<br>
<span class="b-attach" data-size="500" data-hits="83" data-attach-id="65031" data-attach-post-id="3893421">
			<span class="b-attach__title"></span><a class='b-attach-link' href='https://forum.sources.ru/index.php?act=Attach&amp;type=post&amp;id=3893421&amp;attach_id=65031' title='Скачать файл' target='_blank'>____________________________________________________________.zip</a> (, : 83)
		</span>]]></description>
        <author>tumanovalex</author>
        <category>C/C++: Общие вопросы</category>
      </item>
	
      </channel>
      </rss>
	