<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; AHK: Сохранение файла с BOM]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=12545&amp;type=atom" />
	<updated>2017-03-16T23:15:40Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=12545</id>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113851#p113851" />
			<content type="html"><![CDATA[<p>И то верно. Сам же пользуюсь постоянно. Иногда полезно наговорить херни, в обществе тех, кто умеет наиболее болезненно вернуть беседу в нужное русло. Закрепляет материал. Благодарю. <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[KusochekDobra]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33846</uri>
			</author>
			<updated>2017-03-16T23:15:40Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113851#p113851</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113850#p113850" />
			<content type="html"><![CDATA[<p>А вы реально пробовали писать в файл, открытый для чтения? Я вот пробовал, однажды.<br />Вы так убедительно написали, что сейчас попробовал еще раз :-).</p>]]></content>
			<author>
				<name><![CDATA[stealzy]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=31937</uri>
			</author>
			<updated>2017-03-16T22:53:40Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113850#p113850</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113849#p113849" />
			<content type="html"><![CDATA[<p>В сущности, я Вам то же самое, что и Отец всея Autohotkey написал(это даже в справке есть). Если посмотреть содержимое тега &quot;code&quot; на предмет сравнения с примером из поста №1, обозначенный момент можно заметить. Разница только в том, что в Вашем последнем примере, получаете кодировку исходника, чтобы сообщить её в процедуру записи, которую, Вы вначале действительно не забыли, но описали несколько не в том месте, для того чтобы получать ожидаемый результат, о согласии с чем так же свидетельствует отсутствие этой строки в Вашем, последнем примере.</p><p>Строка же:<br /></p><div class="codebox"><pre><code>
FileEncoding, UTF-8
</code></pre></div><p>устанавливает нужную кодировку в качестве дефолтной и если предполагается пользовать её повсеместно, это избавляет от необходимости сообщать её соответствующим процедурам(о чём так же упомянуто в справке). А ещё, он Вам на своём &quot;буржуйском&quot; приводил и другой пример, что если вы собираетесь реализовать принцип, который, вероятно, демонстрирует Ваш сценарий, то не нужно не только закрывать файл, но и вновь его открывать. Контент файла у Вас уже есть, производите его модификацию согласно условиям, сообщаете объекту новый размер равный нулю и пишете изменённый контент обратно в объект:<br /></p><div class="codebox"><pre><code>
file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
encoding := file.Encoding
scriptContent := file.Read()
; file.Close() ; it is not necessary

MsgBox % &quot;Я&quot; . (SubStr(scriptContent, 1, 4) = &quot;file&quot;)

;file := FileOpen(A_ScriptFullPath, &quot;w&quot;, encoding)
file.Length := 0
file.Write(scriptContent)
file.Close()
</code></pre></div><p>Что так же справедливо и для Вашего первого примера:<br /></p><div class="codebox"><pre><code>
file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
encoding := file.Encoding
scriptContent := file.Read()
;file.Close()

MsgBox Кодировка согласно свойству .Encoding`n%encoding%
MsgBox % GetFileBOM(A_ScriptFullPath)
GetFileBOM(file) {
  FileRead,text,*c %file%
  If (0xBFBBEF=NumGet(&amp;text,&quot;UInt&quot;) &amp; 0xFFFFFF)
    Return &quot;UTF-8 BOM&quot;
  else if (0xFFFE=NumGet(&amp;text,&quot;UShort&quot;) || 0xFEFF=NumGet(&amp;text,&quot;UShort&quot;))
    Return &quot;UTF-16 BOM&quot;
  FileGetSize,size,%file%
  Return StrLen(StrGet(&amp;text,&quot;UTF-8&quot;))=size?&quot;ANSI&quot;:&quot;UTF-8 no BOM&quot;
}

;file := FileOpen(A_ScriptFullPath, &quot;w&quot;,&quot;UTF-8&quot;)
;file.Encoding := encoding
file.Length:=0
file.Write(scriptContent)
file.Close()
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[KusochekDobra]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33846</uri>
			</author>
			<updated>2017-03-16T22:26:35Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113849#p113849</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113844#p113844" />
			<content type="html"><![CDATA[<p>Спасибо, но кодировку я не забывал - <em>file.Encoding := encoding</em>. И кстати, честное UTF-8 получается. Без BOM :^).<br />Я запостил свой велосипед по спасению BOM буржуям, и сам <strong>lexikos</strong> ответил мне, что для этого можно указывать кодировку в параметрах FileOpen().<br />Сейчас так и сделал:<br /></p><div class="codebox"><pre><code>file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
encoding := file.Encoding
scriptContent := file.Read()
; file.Close() ; it is not necessary

MsgBox % &quot;Я&quot; . (SubStr(scriptContent, 1, 4) = &quot;file&quot;)

file := FileOpen(A_ScriptFullPath, &quot;w&quot;, encoding)
file.Write(scriptContent)
file.Close()</code></pre></div>]]></content>
			<author>
				<name><![CDATA[stealzy]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=31937</uri>
			</author>
			<updated>2017-03-16T18:52:37Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113844#p113844</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113832#p113832" />
			<content type="html"><![CDATA[<p>Привет. Вы забыли кодировку указать при записи:<br /></p><div class="codebox"><pre><code>
file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
encoding := file.Encoding
scriptContent := file.Read()
file.Close()

MsgBox Кодировка согласно свойству .Encoding`n%encoding%
MsgBox % GetFileBOM(A_ScriptFullPath)
GetFileBOM(file) {
  FileRead,text,*c %file%
  If (0xBFBBEF=NumGet(&amp;text,&quot;UInt&quot;) &amp; 0xFFFFFF)
    Return &quot;UTF-8 BOM&quot;
  else if (0xFFFE=NumGet(&amp;text,&quot;UShort&quot;) || 0xFEFF=NumGet(&amp;text,&quot;UShort&quot;))
    Return &quot;UTF-16 BOM&quot;
  FileGetSize,size,%file%
  Return StrLen(StrGet(&amp;text,&quot;UTF-8&quot;))=size?&quot;ANSI&quot;:&quot;UTF-8 no BOM&quot;
}

file := FileOpen(A_ScriptFullPath, &quot;w&quot;,&quot;UTF-8&quot;)
file.Encoding := encoding
file.Write(scriptContent)
file.Close()
</code></pre></div><p>Если это указывать явно, то проблемы не будет. Или вместо этого добавить в начало файла строку:<br /></p><div class="codebox"><pre><code>
FileEncoding, UTF-8
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[KusochekDobra]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33846</uri>
			</author>
			<updated>2017-03-16T10:09:42Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113832#p113832</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113828#p113828" />
			<content type="html"><![CDATA[<p>В таком случае BOM попадает в MsgBox, хоть его там и не видно,<br />но если совершать операции с текстом, он может мешаться.<br />Получение текста без BOM (раскомментировать):<br /></p><div class="codebox"><pre><code>file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
;If (file.Pos &lt;&gt; 0) { ; BOM
	file.Pos := 0 ; for take BOM
	;BOM := file.Read(1) ; now pointer file.Pos = 3 or 2 again :-)
;}
encoding := file.Encoding
scriptContent := file.Read()
file.Close()

MsgBox % SubStr(scriptContent, 1, 4) = &quot;file&quot;

file := FileOpen(A_ScriptFullPath, &quot;w&quot;)
file.Encoding := encoding
file.Write(BOM NewScriptContent)
file.Close()</code></pre></div>]]></content>
			<author>
				<name><![CDATA[stealzy]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=31937</uri>
			</author>
			<updated>2017-03-15T16:58:22Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113828#p113828</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113826#p113826" />
			<content type="html"><![CDATA[<p>При открытии файла с BOM указатель переносится сразу за него, и, соответственно, BOM в переменную <em>scriptContent </em>не попадает.</p><div class="quotebox"><blockquote><p>When a file containing a UTF-8 or UTF-16 byte order mark (BOM) is opened with read access, the BOM is excluded from the output by positioning the file pointer after it. Therefore, File.Position may report 3 or 2 immediately after opening the file.</p></blockquote></div><p>Вот так сработает:</p><div class="codebox"><pre><code>file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
MsgBox, % file.Pos
file.Pos := 0
encoding := file.Encoding
scriptContent := file.Read()
file.Close()

MsgBox % encoding

file := FileOpen(A_ScriptFullPath, &quot;w&quot;)
file.Encoding := encoding
file.Write(scriptContent)
file.Close()</code></pre></div>]]></content>
			<author>
				<name><![CDATA[teadrinker]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24515</uri>
			</author>
			<updated>2017-03-15T13:17:44Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113826#p113826</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[AHK: Сохранение файла с BOM]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=113824#p113824" />
			<content type="html"><![CDATA[<p>Данный скрипт (сохраненный в UTF-8 с BOM) успешно переписывает себя, но BOM теряет, соответственно, при последующих запусках, интерпретатор считает что кодировка CP12xx. Запускать дважды.<br /></p><div class="codebox"><pre><code>file := FileOpen(A_ScriptFullPath, &quot;r&quot;)
encoding := file.Encoding
scriptContent := file.Read()
file.Close()

MsgBox Кодировка согласно свойству .Encoding`n%encoding%
MsgBox % GetFileBOM(A_ScriptFullPath)
GetFileBOM(file) {
  FileRead,text,*c %file%
  If (0xBFBBEF=NumGet(&amp;text,&quot;UInt&quot;) &amp; 0xFFFFFF)
    Return &quot;UTF-8 BOM&quot;
  else if (0xFFFE=NumGet(&amp;text,&quot;UShort&quot;) || 0xFEFF=NumGet(&amp;text,&quot;UShort&quot;))
    Return &quot;UTF-16 BOM&quot;
  FileGetSize,size,%file%
  Return StrLen(StrGet(&amp;text,&quot;UTF-8&quot;))=size?&quot;ANSI&quot;:&quot;UTF-8 no BOM&quot;
}

file := FileOpen(A_ScriptFullPath, &quot;w&quot;)
file.Encoding := encoding
file.Write(scriptContent)
file.Close()</code></pre></div><p>В справке по FileOpen() написано:</p><div class="quotebox"><blockquote><p>When a UTF-8 or UTF-16 file is created, a byte order mark is written to the file unless Encoding (or A_FileEncoding if Encoding is omitted) contains &quot;UTF-8-RAW&quot; or &quot;UTF-16-RAW&quot;.</p></blockquote></div><p>Почему-то в моем примере BOM не записывается.<br />Пока на ум ничего не приходит, разве что при сохранении добавлять в начало Hex-содержимого файла ï»¿.</p>]]></content>
			<author>
				<name><![CDATA[stealzy]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=31937</uri>
			</author>
			<updated>2017-03-15T11:13:02Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=113824#p113824</id>
		</entry>
</feed>
