本文主要内容是区分C语言、python、perl读写文件代码,便于记忆
1 初始化
C语言需要先声明文件对象
perl可以声明返回值也可不声明
FILE *fp = NULL;
my $value;
2 打开文件
C语言使用fopen()
python和perl使用open()
但C语言和python语言的输入值一样
fp = fopen(“xxx.txt”, “r”);
f = open(“xxx.txt”, “r”)
perl第一个参数为文件句柄,第二个为方式以及文件名,大于号为读,小于号为写
$value = open(file, “> xxx.log”); #以只读的方式
3 读写方式
读写的函数有很多,下面只举例说明一种,便于记忆
C语言的一种方式为fgetc()、fputs()
python的一种方式为f.read() f.write(“string”)
perl的读写在打开时候就完成
4 关闭文件
C语言
fclose(fp);
python
f.close()
perl
close(file)
最后附上三者的基本代码
#include <stdio.h>
// 读文件
int main() {
FILE *fp = NULL;
char ch;
// 打开文件
fp = fopen("xxx.txt", "r");
if(fp != NULL) {
while(!feof(fp)) // 文件指针到达文件末尾
printf("%c", fgetc(fp));
}
else
printf("fail to open!\n");
fclose(fp);
return 0;
}
// 写文件
int main()
{
FILE *fp = NULL;
char ch;
fp = fopen("xxx.txt", "w");
if(fp != NULL)
{
fputs("ilovec", fp);
}
else
printf("fail to open!\n");
fclose(fp);
return 0;
}
# 读文件
f = open("xxx.txt", "r");
content = f.read()
print('content:' + content)
f.close()
# 写文件
f = open("xxx.txt", "w")
f.write("abcd")
f.close()
# open file to read
open(file1, "<xxx.txt");
# open file to write
open(file2, ">xxx.txt");
# copy data from file1 to file2
while(<file1>)
{
print file2 $_;
}
close(file1);
close(file2);