Delphi读取文件和写入文件总结
---
读取文件:
1,关联文件:AssignFile(pMyFile,'c:\ttt.csv');
2,打开文件:Reset(pMyFile);
3,读取一行:Readln(pMyFile,pStr);
4,关闭文件:CloseFile(pMyFile);
示例:
procedure TForm1.Button1Click(Sender: TObject);
var
pMyFile:textfile;
pStr : string;
begin
if OpenDialog1.Execute then begin
Assignfile(pMyFile,OpenDialog1.FileName);
Reset(pMyFile);
while not Eof(pMyFile) do begin
Readln(pMyFile,pStr);
//fn_DelStock(pStr); //使用读取的字符串相关语句
next;
end;
CloseFile(pMyFile);
end;
end;
+++
写入文件:
1,关联文件:AssignFile(pMyFile,'c:\ttt.csv');
2,打开文件:ReWrite(pMyFile); //如果文件不存在,用ReWrite打开
Append(pMyFile); //如果文件已经存在,追加内容,用Append打开
3,写入一行:WriteLn(pMyFile,pStr);
4,关闭文件:CloseFile(pMyFile);
示例:
procedure TForm1.WLog(pMsg: string);
var
pFObJect,pFPath,pFName: string;
pMyFile: textFile;
pStr: string;
begin
pFPath:='d:';
pFName:='StockDel_'+formatDateTime('yyyymmddhhmmss',now);
pFObject:=pFPath + '\' + pFName + '.csv';
try
AssignFile(pMyFile,pFObject);
if FileExists(pFObject)=false then
ReWrite(pMyFile)
else
Append(pMyFile);
pStr:=pMsg;
WriteLn(pMyFile,pStr);
finally
CloseFile(pMyFile);
end;
end;
+++
公用写日志文件过程
//==ini文件设置:
'日志选项和文件 当Log_Flag=N时不记录,否则均记录
Log_Flag=1
Log_PathFileName=\\10.105.10.12\c\Prd_220_File\log.dat
//==声明全局变量
x_pLogFile: string; //日志文件名称
x_pLogFlag: string; //是否记录日志,N:不写日志
x_pFindLogFile: boolean; //记录日志文件是否存在,避免每次写日志时都要判断。
//==过程声明
procedure cpWriteLog(pFObject:string; pTxt:string; pMode:byte);
//==初始化全局变量
procedure TForm1.FormCreate(Sender: TObject);
begin
x_pLogFile:= cfReadIniFile(X_cProgID,'Log_PathFileName','c:\ENRC0300_Log.txt');
x_pLogFlag:= cfReadIniFile(X_cProgID,'Log_Flag','N');
end;
//==写日志过程
procedure cpWriteLog(pFObject:string; pTxt:string; pMode:byte);
var
pMyFile: textFile;
begin
if x_pLogFlag='N' then exit;
try
AssignFile(pMyFile,pFObject);
if pMode=1 then pTxt:= DateTimeToStr(Now)+' '+pTxt;
if x_pFindLogFile=True then
append(pMyFile)
else begin
if FileExists(pFObject) then
append(pMyFile)
else
reWrite(pMyFile);
x_pFindLogFile:=true;
end;
WriteLn(pMyFile,pTxt);
finally
CloseFile(pMyFile);
end;
end;
//==调用过程
x_pMsg:='导出
程序['+X_cProgID+']打开,';
cpWriteLog(x_pLog
File,x_pMsg,1);
Delphi文件操作所涉及的一些函数
RemoveDirectory
//获取当前文件夹 GetCurrentDir
//设置当前文件夹 SetCurrentDir; ChDir; SetCurrentDirectory
//获取指定驱动器的当前路径名 GetDir
//文件改名 RenameFile
//建立文件夹 CreateDir; CreateDirectory; ForceDirectories
//删除空文件夹 RemoveDir; RemoveDirectory
//建立新文件 FileCreate
//获取当前文件的版本号 GetFileVersion
//获取磁盘空间 DiskSize; DiskFree
//
搜索文件 FindFirst; FindNext; FindClose
//读取与设置文件属性 FileGetAttr; FileSetAttr
//获取文件的创建时间 FileAge; FileDateToDateTime
Delphi代码
//判断文件是否存在 FileExists
var
f: string;
begin
f := 'c:\temp\test.txt';
if not FileExists(f) then
begin
//如果文件不存在
end;
end;
--------------------------------------------------------------------------------
//判断文件夹是否