Writeln question lazarus / 61-Beginners ---------------------------------------------------------------------- JLWest · 2021-02-05 02:30 I asked this question before but can't fine the answer. Would like to write a text file in fixed fields to look like this: xxxxxx                               xxxxxxxxxxxxxxxx     xxxxxxxxxx I think it's something like:   Writeln (Field1:47);   Writeln (Field2:35);   Writeln(Field3:25); I don't know. Thanks ---------------------------------------------------------------------- egsuh · 2021-02-05 02:48 Writeln adds carriage return, which changes line. "Write" do not change lines. So you should write either:       Write(field1:47);       Write(Field2: 35);       Writeln(Field3: 25); or      Writeln(field1:47, field2:35, field3:25);   But if you want to write fixed record-length text file, you should not use writeln. Please refer following sites. https://chapmanworld.com/2015/02/19/file-handling-in-delphi-object- pascal/ https://wiki.freepascal.org/File_Handling_In_Pascal ---------------------------------------------------------------------- lucamar · 2021-02-05 05:03 Note that if followed with a width specification, as in field1:47, the output will be right-justified, not left as in your example. To write left-justified fields the common way to do it is to convert them to strings padded to the appropiate length and Write (or WriteLn) those strings. There are lots of conversion functions and type helpers to do that, e.g. the all-powerful Format() (which I tend to use everywhere), but WriteStr() combined with PadRight() (from StrUtils) is often a simple and convenient way to do it: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Formatting; uses  SysUtils, {for Format()}  StrUtils; {for PadRight()} var  Field1, Field2, Field3: Integer; function CvtToStr(const n, width: Integer): String;begin  WriteStr(Result, n);  Result := PadRight(Result, width);end; begin  Field1 := 241;  Field2 := 734;  Field3 := 693;  {We could use WriteLn instead of Write, since it goes to screen;   instead I added a couple empty Writeln() to separate the lines   while keeping it as if we were writing to a file}  { Using WriteStr+PadRight }  Write('WriteStr: [',        CvtToStr(Field1, 47),        CvtToStr(Field2, 35),        CvtToStr(Field3, 25),        ']');  WriteLn();   { Using Format; here you see why I prefer it ;-) }  Write('Format  : [',        Format('%-47d%-35d%-25d', [Field1, Field2, Field3]),        ']');  WriteLn();end. The result is: Code: [Select]lucamar@Diana:~/SoftDev/Test/temp/$ ./Formatting WriteStr: [241                                            734                              693                      ] Format  : [241                                            734                              693                      ] ---------------------------------------------------------------------- marcov · 2021-02-05 06:40 Note also that writeln(x:11); will become wider when "x" is longer than 11 characters, this syntax doesn't truncate. If tight control is required it is wiser to go directly to the manual construction of a string. It might also be worthwhile to check if the csvdocument unit allows for fixed field files. ---------------------------------------------------------------------- lucamar · 2021-02-05 08:19 Quote from: marcov on February 05, 2021, 07:40:34 amIt might also be worthwhile to check if the csvdocument unit allows for fixed field files. I haven't looked but ... Wouldn't that be quite contrary to what they were designed for? Assuming that by "fixed" you mean "fixed size", of course; in that case it would make little sense to have also field separators ... Unless one is of the "belt and suspenders" tribe, of course ---------------------------------------------------------------------- JLWest · 2021-02-05 09:13 I get a runtime error 103 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  procedure TForm1.FileFormater(AFile : String);  Var i : integer = -1;   OutFile : Textfile;   LineOut  : String = '';   Fld1,Fld2 : String;  begin   AssignFile(OutFile, AFile);  Try   Rewrite(OutFile);   for i := 0 to LBWork.Items.Count -1 do begin       Fld2 := LBWork.Items[i];                                // Runtime error here       Fld1 := Copy2SpaceDel(Fld2);       Write(Fld1:45);       WriteLn(Fld2:65);    end;    finally     CloseFile(OutFile);   end;  end;     Guess I'll try the other way. ---------------------------------------------------------------------- speter · 2021-02-05 09:23 I don't understand how you can get a 103 (File not open) at line 11 of your code? A 103 should be referring to line 13, 14 or 17. BUT, line 13 & 14 should be: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   write(outfile,fld1:45);  writeln(outfile,fld2:65); In very old versions of Pascal, write and writeln send data to the "output" file; and so you could get a 103 error if you didn't open "output" (to write on the console). I'm not sure what Laz/FPC does with a write() that doesn't specify a file!? cheers S. ---------------------------------------------------------------------- MarkMLl · 2021-02-05 09:42 Quote from: speter on February 05, 2021, 10:23:14 amI'm not sure what Laz/FPC does with a write() that doesn't specify a file!? Sends it to the default output device. I suspect the behaviour when e.g. not run from a command line might be platform-specific... Linux generally discards output silently. MarkMLl ---------------------------------------------------------------------- JLWest · 2021-02-05 09:42 @speter That worked. Here is the output: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Airports                     |D:\QLUI\airports\|5000|Cities                     |D:\QLUI\cities\|5000|Farm                       |D:\QLUI\farm\|5000|Free Pascal             |X:\FreePascal\|4000|Passwords                            |f:\passwords\|5000|       Phonebook                          |f:\phonebook\|5000|Trash                                      |X:\trash\|5000|War                       |D:\QLUI\war\|5000| What I'm looking for is: The file is loaded into a listbox and the user selects which one he wants to load. He should see the Cities, Farm, Free Pascal ect. but not the bared items to the right. Note: it doesn't show right but the bared items on the right should be lined up. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Airports                     |D:\QLUI\airports\|5000|Cities                                             |D:\QLUI\cities\|5000|Farm                                              |D:\QLUI\farm\|5000|Free Pascal                                  |X:\FreePascal\|4000|Passwords                                      |f:\passwords\|5000|   Phonebook                                     |f:\phonebook\|5000|Trash                                             |X:\trash\|5000|War                                               |D:\QLUI\war\|5000| ---------------------------------------------------------------------- MarkMLl · 2021-02-05 09:50 Quote from: lucamar on February 05, 2021, 06:03:02 amthe all-powerful Format() (which I tend to use everywhere), I always feel guilty when using it, due to the sloppiness of the array parameter. However its practical usability is generally better than Write()'s :x:y notation, which is also a messy single-purpose extension to Pascal's basic syntax... I'm not saying there that it was tacked on post-J&W, just that it breaks the regularity of the syntax. It strikes me as a pity that Format() isn't extensible/redefinable, i.e. with something like Format('%d%s', [something, somethingelse]) being parsed through a callback so that padding etc. rules could be overridden e.g. to always pad hex with zeroes rather than spaces. MarkMLl ---------------------------------------------------------------------- speter · 2021-02-05 11:22 Hmmm, I haven't used listbox much but I don't see why you'd need such a complex file format! If you are interested, have a look at the attached project. It reads a comma delimited file and puts the 'name' portion into a list box, then displays the 'path' portion when the user selects a name... Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  k : tstringlist; procedure TForm1.FormCreate(Sender: TObject);var  tsa : tstringarray;  s : string;begin  k := tstringlist.create;  k.LoadFromFile('file.txt');  for s in k do    begin      tsa := s.Split(',');      listbox1.Items.add(tsa[0]);    end;end; procedure TForm1.ListBox1SelectionChange(Sender: TObject; User: boolean);var  s : string;  tsa : tstringarray;begin  for s in k do    begin      tsa := s.Split(',');      if tsa[0] = listbox1.items[listbox1.ItemIndex] then        begin          memo1.append(tsa[1]);          exit;      end;    end;end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);begin  k.free;end; My code is very inefficient (it parses the text every time an items is selected; but you'll get the idea. The text file is based on your sample (and is included in project1.zip): Code: [Select]Airports, |D:\QLUI\airports\|5000| Cities, |D:\QLUI\cities\|5000| Farm, |D:\QLUI\farm\|5000| Free Pascal, |X:\FreePascal\|4000| Passwords, |f:\passwords\|5000|      Phonebook, |f:\phonebook\|5000| Trash, |X:\trash\|5000| War, |D:\QLUI\war\|5000| cheers S. ---------------------------------------------------------------------- Kays · 2021-02-05 12:56 Quote from: lucamar on February 05, 2021, 06:03:02 amNote that if followed with a width specification, as in field1:47, the output will be right-justified, not left as in your example. To write left-justified fields the common way to do it is to convert them to strings padded to the appropiate length and Write (or WriteLn) those strings. […]If you are already using sysUtils you can use tStringHelper.padRight directly, no need for uses strUtils. Quote from: egsuh on February 05, 2021, 03:48:15 am[…] write fixed record-length […]There is also the (now rather archaic) solution of using actual fixed-length records… Quote from: marcov on February 05, 2021, 07:40:34 amNote also that writeln(x:11); will become wider when "x" is longer than 11 characters, this syntax doesn't truncate. […]The FPC allows writing strings to array[…] of char. Given strings will be (silently) truncated to the destination’s maximum capacity. However, the FPC pads the array[…] of char with #0, so this approach is only actually useful if you intend to re-read your text by a machine, a different program for example. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program writeLineQuestion(output);type        tableRow = record                      left: array[1..47] of char;                        middle: array[1..35] of char;                        right: array[1..25] of char;                end;var        line: tableRow;begin        with line do        begin                left := 'Hello';                middle := 'world';                right := '!';                writeLn(left, middle, right);        end;end.The beauty of this pattern, though, is that you can also read and write entire records to a file of tableRow (“typed file”) in one read/write statement. PS: The GPC apparently pads array[…] of char strings with #20. PPS: Note, {$modeSwitch unicodeStrings+} redefines the meaning of char. ---------------------------------------------------------------------- lucamar · 2021-02-05 14:39 Quote from: speter on February 05, 2021, 10:23:14 amI'm not sure what Laz/FPC does with a write() that doesn't specify a file!? As Mark said, it sends it to the Output file (normally the console) but that's closed by default in LCL programs and the effect depends on the target OS: Linux (and most other *nixen) silently ignores it but Windows (and some other which I don't remember) do indeed complain loudly ... raising an error 103, logically enough. Quote from: MarkMLl on February 05, 2021, 10:50:52 amI always feel guilty when using it, due to the sloppiness of the array parameter. [...] It strikes me as a pity that Format() isn't extensible/redefinable, i.e. with something like Format('%d%s', [something, somethingelse]) being parsed through a callback so that padding etc. rules could be overridden e.g. to always pad hex with zeroes rather than spaces. I use it (and have used it, and shall keep using it) so many times in so many different programs that feeling guilty would make of me kind of an hypocrite, so I don't feel guilty at all. I've even ended finding some queer kind of beauty in the "array of const" sintax I've also found it a little "constricting" some (few) times. I suppose, though, that extending it even more would probably make it a little unwieldly so I don't mind (much) having to find a workaround for those few times. Quote from: Kays on February 05, 2021, 01:56:41 pmQuote from: lucamar on February 05, 2021, 06:03:02 amTo write left-justified fields the common way to do it is to convert them to strings padded to the appropiate length and Write (or WriteLn) those strings. […]If you are already using sysUtils you can use tStringHelper.padRight directly, no need for uses strUtils. You're completely right, of course. It's just that I tend to use the good old functions rather than the "new" type helpers; pure inertia, probably. Also, most helpers in SysUtils end up calling exactly those same functions so I usually end up "jumping the intermediary" almost unconsciously unless there is some clarity gained by doing otherwise.