【C与python与perl】读写文件程序的区别

本文主要内容是区分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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值