Recent

Author Topic: How can read a file and then add its contents to another file  (Read 4339 times)

samoraj

  • New Member
  • *
  • Posts: 22
I want to read a file from several lines and then add its contents to another file but I do not know how to read from one file and write to another file. Maybe I need some buffer ?  %)

Handoko

  • Hero Member
  • *****
  • Posts: 5158
  • My goal: build my own game engine using Lazarus
Re: How can read a file and then add its contents to another file
« Reply #1 on: July 15, 2017, 05:04:10 am »
What is type of file? I guess you meant normal text, right?

This link below can give you some basic ideas how to do it. If it is a text file, using TStringList will be easier.

http://wiki.freepascal.org/File_Handling_In_Pascal
« Last Edit: July 15, 2017, 05:06:04 am by Handoko »

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: How can read a file and then add its contents to another file
« Reply #2 on: July 15, 2017, 05:55:54 am »
Here's a textfile example.

Code: Pascal  [Select][+][-]
  1. program ReadWriteTextFiles;
  2.  
  3. {$Mode objfpc}{$H+}
  4.  
  5. uses classes, sysutils;
  6.  
  7. procedure WriteTextFile(const aFilename, aCommaList: string);
  8. var
  9.   sl: TStringList;
  10. begin
  11.   Assert((aFilename<>'')and(aCommaList<>''),'WriteTextFile: invalid parameter(s)');
  12.   sl:=TStringList.Create;
  13.   try
  14.     sl.CommaText:=aCommaList;
  15.     sl.SaveToFile(aFilename);
  16.   finally
  17.     sl.Free;
  18.   end;
  19. end;
  20.  
  21. function SaveLinesOfFile1ToFile2(const aFilename1, aFilename2: string; aStartLine, anEndLine: Word): Boolean;
  22. var
  23.   sl, sl2: TStringList;
  24.   i: Integer;
  25. begin
  26.   Assert((aFilename1<>'')and(aFilename2<>''),'SaveLinesOfFile1ToFile2: invalid parameter(s)');
  27.   Assert(FileExists(aFilename1),aFilename1+' does not exist');
  28.   Assert(aStartLine < anEndLine,'SaveLinesOfFile1ToFile2: invalid parameters');
  29.   Result:=False;
  30.   sl:=TStringList.Create;
  31.   try
  32.     sl.LoadFromFile(aFilename1);
  33.     if (anEndLine > sl.Count-1) then
  34.       Exit;
  35.     sl2:=TStringList.Create;
  36.     try
  37.       for i:=aStartLine to anEndLine do
  38.         sl2.Add(sl[i]);
  39.       sl2.SaveToFile(aFilename2);
  40.     finally
  41.       sl2.Free;
  42.     end;
  43.   finally
  44.     sl.Free;
  45.   end;
  46.   Result:=True;
  47. end;
  48.  
  49. const
  50.   Filename1 = 'test.txt';
  51.   Filename2 = 'partcopy.txt';
  52.   start = 3;
  53.   finish = 6;
  54. begin
  55.   WriteTextFile(Filename1,'zero,one,two,three,four,five,six,seven,eight,nine,ten');
  56.  
  57.   if SaveLinesOfFile1ToFile2(Filename1, Filename2, start, finish) then
  58.     WriteLn('Copied lines ',start,' to ',finish,' from ',Filename1,' to ',Filename2)
  59.   else WriteLn('Writing or part copying of files failed');
  60.  
  61.   ReadLn;
  62. end.

Thaddy

  • Hero Member
  • *****
  • Posts: 14390
  • Sensorship about opinions does not belong here.
Re: How can read a file and then add its contents to another file
« Reply #3 on: July 15, 2017, 08:15:12 am »
Streams are easy.
Takes two existing files and appends the first to the second.
Code: Pascal  [Select][+][-]
  1. program inoutstream;
  2. uses
  3.   classes,sysutils;
  4. var
  5. Instream,OutStream:TFilestream;
  6. begin
  7. if (ParamCount = 2) and
  8.   FileExists(ParamStr(1)) and
  9.   FileExists(ParamStr(2)) then
  10.   begin
  11.   instream := TFilestream.Create(ParamStr(1), fmOpenRead);
  12.   try
  13.     outstream :=TFilestream.Create(Paramstr(2), fmOpenwrite);
  14.     try
  15.       outstream.position := Outstream.size;
  16.       outstream.copyfrom(instream,0);// appends
  17.     finally
  18.       instream.free;
  19.     end;
  20.   finally
  21.     outstream.free;
  22.   end;
  23.   end else writeln('use: inoutstream <infile> <outfile>');
  24. end.


I will add this to the wiki, because it is a much better example  8-) The wiki is cluttered and needs a rewrite because of hopelessly incapable example code. Almost everything works, but almost all the object oriented examples are plain bad. It is on my agenda.
« Last Edit: July 15, 2017, 09:29:47 am by Thaddy »
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

samoraj

  • New Member
  • *
  • Posts: 22
Re: How can read a file and then add its contents to another file
« Reply #4 on: July 16, 2017, 12:04:59 am »
Hello Thaddy, i have 2 files 'C:\test1.txt' and 'C:\test2.txt' . How to implement them in your code ? :'(

Bart

  • Hero Member
  • *****
  • Posts: 5290
    • Bart en Mariska's Webstek
Re: How can read a file and then add its contents to another file
« Reply #5 on: July 16, 2017, 12:19:45 am »
The old fashioned way. Works for textfiles only.

Untested code ...
Code: Pascal  [Select][+][-]
  1. uses sysutils;
  2.  
  3. var
  4.   File1, File2: TextFile;
  5.   S: String;
  6. ...
  7.   assignfile(File1,'C:\Test1.txt');
  8.   assignfile(File2,'C:\Test2.txt');
  9.   reset(File1); //open for read;
  10.   append(File2); //asumes File2 can be written to, puts filepointer at end of the file
  11.   while not Eof(File1) do
  12.   begin
  13.     readln(File1,S); //read a line frome file1
  14.     writeln(File2,S); //write the line to file2
  15.   end;
  16.   CloseFile(File1);
  17.   CloseFile(File2);
  18. ...
  19.  

Bart

Almir.Bispo

  • Jr. Member
  • **
  • Posts: 91
  • CSV Comp DB is the Best NoSQL
    • CSV Comp DB (NoSQL)
Re: How can read a file and then add its contents to another file
« Reply #6 on: July 16, 2017, 12:54:07 am »
Code: Pascal  [Select][+][-]
  1. procedure add_data;
  2. var f:Tstringlist;
  3.   content:string;
  4. begin
  5. f:= Tstringlist.create;
  6. f.loadfromfile('c:\file1.txt'); //first file
  7. content:=f.text;
  8. f.clear;
  9. f.loadfromfile('c:\file2.txt'); //second
  10. f.add(content);
  11. f.savetofile('c:\file2.txt');// save to  second
  12. f.free;
  13. end;
  14. //how to use
  15. add_data;
  16.  

My Blog : http://adltecnologia.blogspot.com.br
CSV Comp DB Developer {Pascal Lover}

Bart

  • Hero Member
  • *****
  • Posts: 5290
    • Bart en Mariska's Webstek
Re: How can read a file and then add its contents to another file
« Reply #7 on: July 16, 2017, 01:17:22 am »
You can alway let Windows do the job for you ...  O:-)

Code: Pascal  [Select][+][-]
  1. uses
  2.   classes, sysutils, process;
  3.  
  4. var
  5.   Proc: TProcess;
  6. begin
  7.   Proc := TProcess.Create;
  8.   try
  9.     Proc.Executable := 'cmd.exe';
  10.     Proc.Paramters.Add('/c');
  11.     Proc.Paramters.Add('type C:\Text1.txt >> C:\Text2.text');
  12.     Proc.Options := Proc.Options + [poWaitOnExit];
  13.     Proc.Excute;
  14.   finally
  15.     Proc.Free;
  16.   end;
  17. end.
  18.  

Bart

RAW

  • Hero Member
  • *****
  • Posts: 868
Re: How can read a file and then add its contents to another file
« Reply #8 on: July 16, 2017, 01:30:00 am »
Here is a very easy function... should work... feel free to test it...  :D
My first thought... but the question is very vague, you really need to know what kind of files you have (languages) and what you wanna do with it later...

This should be very easy to read...  :D
Code: Pascal  [Select][+][-]
  1. PROGRAM project1;
  2.  {$MODE OBJFPC}{$H+}{$J-}
  3.  USES
  4.   Classes, SysUtils;
  5.  
  6.  
  7.  Function AppendText(strFile1, strFile2, strSaveFile: String): Boolean;
  8.    Var
  9.     sl : TStringlist;
  10.     str: String;
  11.   Begin
  12.    Try
  13.     Result:= False;
  14.  
  15.     sl:= TStringlist.Create;
  16.      Try
  17.       If FileExists(strFile1)
  18.       Then
  19.        Begin
  20.         sl.LoadFromFile(strFile1);
  21.         str:= sl.Text;
  22.        End
  23.       Else Exit;
  24.  
  25.       If FileExists(strFile2)
  26.       Then
  27.        Begin
  28.         sl.LoadFromFile(strFile2);
  29.         str:= str+sl.Text;
  30.        End
  31.       Else Exit;
  32.  
  33.       sl.Text:= str;
  34.       str    := ExtractFilePath(strSaveFile);
  35.  
  36.       If Not DirectoryExists(str)
  37.       Then
  38.        If Not CreateDir(str)
  39.        Then Exit;
  40.  
  41.       sl.SaveToFile(strSaveFile);
  42.  
  43.       If FileExists(strSaveFile)
  44.       Then Result:= True;
  45.      Finally
  46.       sl.Free;
  47.      End;
  48.    Except
  49.     Result:= False;
  50.    End;
  51.   End;
  52.  
  53.  
  54. BEGIN
  55.  If AppendText(
  56.      'I:\(DOWNLOADS)\Hallo.txt',
  57.      'I:\(DOWNLOADS)\Hello.txt',
  58.      'C:\MyFolder\FP.txt')
  59.  Then WriteLn('Done')
  60.  Else WriteLn('Error');
  61.  
  62.  ReadLn;
  63. END.
Windows 7 Pro (x64 Sp1) & Windows XP Pro (x86 Sp3).

ASerge

  • Hero Member
  • *****
  • Posts: 2249
Re: How can read a file and then add its contents to another file
« Reply #9 on: July 16, 2017, 10:11:39 am »
+1 @Thaddy

Thaddy

  • Hero Member
  • *****
  • Posts: 14390
  • Sensorship about opinions does not belong here.
Re: How can read a file and then add its contents to another file
« Reply #10 on: July 16, 2017, 10:27:23 am »
Hello Thaddy, i have 2 files 'C:\test1.txt' and 'C:\test2.txt' . How to implement them in your code ? :'(

Well... how about just typing "inoutstream C:\test1.txt c:\test2.txt" ....
Note on modern Windows you need sufficient access rights to c:\ (as root directory, with admin rights) but my code works in the general case.
Never, ever use c:\ (root) as storage for your own files in anything newer than XP.
« Last Edit: July 16, 2017, 10:30:02 am by Thaddy »
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

 

TinyPortal © 2005-2018