在使用WinCC过程中我们经常会遇到需要读写TXT文档的情况,以下代码供大家参考。
C脚本:
HelpStr 用于存储文本内容,由于使用字符串指针,文本长度理论上可以达到无限长。
tmp 用于存放每行读取的内容。
txt 用于存放文本文件的地址。
ChrNumLine 设定每行读取的长度。
char tmp[255];
char *HelpStr;
char txt[255];
int ChrNumLine=38;
FILE *fp;
BOOL ret;
sprintf(txt,"%s273\\HelpFile\\%s.txt",PrjPath (),lpszObjectName);
fp=fopen(txt,"r");
if (fp==NULL)
{
printf("\r\nOpen File : %s Failed!",txt);
sprintf(HelpStr,"\r\nError!\r\nThe Help file - %s does not exit!",txt);
}
else
{
rewind(fp);
while(!feof(fp))
{
fgets(tmp,ChrNumLine,fp);
strcat(HelpStr,tmp);
strcat(HelpStr,"\r\n");
}
}
ret=fclose(fp);
if (ret!=0) printf("\r\nError In fclose file %s",txt);
SetText("Help_Content.pdl","Main",HelpStr);
vb脚本:
Function ReadAllTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("s cripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadAllTextFile = f.ReadAll
End Function
Private Sub Command1_Click()
If Dir("d:\temp") = " " Then MkDir "d:\temp"
Open "d:\temp\abc.txt" For Output As #1
Print #1, Text1.Text Close #1
End Sub
Private Sub Command1_Click()
Dim txtStream As TextStream
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(App.Path & "\abc.txt", ForWriting, True)
End Sub
Private Sub Command2_Click()
Open "F:\TEST\b.txt" For Output As #1
Print #1, Text1.Text
Close
End Sub
Private Sub Command1_Click()
Dim str
Open "F:\TEST\a.txt" For Append As #1
str = Text1.Text
Write #1, str
Close #1
End Sub