How can I easily determine the last charachter of a file?
ProtectAndHide
ProtectAndHide at gmail.com
Wed Feb 15 10:23:29 UTC 2023
On Tuesday, 14 February 2023 at 18:30:05 UTC, seany wrote:
> Hello
>
> Consider the content of a file
>
> ````
> First line \n
> Second line ....
> ....
> data data data data ... last char
>
> ````
>
> My goal is to find out whether the last character is a new line
> or not. Please not, it will be sufficient if this works on
> Linux.
>
> More specifically I want to insert a new line at the end of the
> file. File.writeline inserts a line at the end of the _newly
> added line_.
>
> Thus if I had
>
>
> ````
> First line \n
> Second line ....
> ....
> data data data data ... non-NL-char
>
> ````
>
> and wanted to insert : `newline-word-word-word ... non-NLchar`
>
> Via `file.writeln`, it would end up as
>
> ````
> First line \n
> Second line ....
> ....
> data data data data ... non-NL-char{no newline or whitespace
> here}Newline-word-word-word ... non-NLchar{newline}
>
> ````
>
> This is not unexpected. But, I want to make sure, that my
> appending automatically adds a new line. However, it should not
> add empty lines.
>
> One brute force method is to copy every line of the file to a
> temp file or in the RAM and then write back in the original
> file. I would like to avoid that if possible.
>
> Thanks.
Building on previous response:
module test;
@safe:
import std;
void main()
{
File myFile = "somefile.txt";
myFile.seek(-1, SEEK_END);
ubyte[1] c;
() @trusted { myFile.rawRead(c[]); } ();
if(ControlChar.lf == c[0]) // is this portable??
writeln("yep, last char is a linefeed.");
else
writeln("nope. last char is not a linefeed.");
}
More information about the Digitalmars-d-learn
mailing list