1、cat命令,用于查看文件内容,tac命令,从最后一行开始显示。
2、nl命令,在显示的时候输出行号,more命令,用于一页一页的显示文件内容等。
Linux下C语言的文件(fputc,fgetc,fwrite,fread对文件读写 *** 作)
//
fputc 向文件写入字符
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp
char ch
if((fp=fopen("test.txt","w"))==NULL)
{
printf("不能打开文件\n")
exit(0)
}
while ((ch=getchar())!='\n')
fputc( ch, fp )
fclose(fp)
}
-------------
小提示:
fp=fopen("test.txt","w") ,把"w"改为 "a" 可以创建文件并且追加写入内容
exit(0)需要包含 stdlib.h 头文件,才能使用
//
fgetc 读取字符
#include <stdio.h>
#include <stdlib.h>
main( int argc, char *argv[] )
{
char ch
FILE *fp
int i
if((fp=fopen(argv[1],"r"))==NULL)
{
printf("不能打开文件\n")
exit(0)
}
while ((ch=fgetc(fp))!=EOF)
putchar(ch)
fclose(fp)
}
文件结尾,通过判断 EOF
//
fwrite 的使用
使数组或结构体等类型可以进行一次性读写
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp1
int i
struct student{
char name[10]
int age
float score[2]
char addr[15]
}stu
if((fp1=fopen("test.txt","wb"))==NULL)
{
printf("不能打开文件")
exit(0)
}
printf("请输入信息,姓名 年龄 分数1 分数2 地址:\n")
for( i=0i<2i++)
{
scanf("%s %d %f %f %s",stu.name,&stu.age,&stu.score[0],&stu.score[1], stu.addr)
fwrite(&stu,sizeof(stu),1,fp1)
}
fclose(fp1)
}
//
fread 的使用
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp1
int i
struct student{
char name[10]
int age
float score[2]
char addr[15]
}stu
if((fp1=fopen("test.txt","rb"))==NULL)
{
printf("不能打开文件")
exit(0)
}
printf("读取文件的内容如下:\n")
for (i=0i<2i++)
{
fread(&stu,sizeof(stu),1,fp1)
printf("%s %d %7.2f %7.2f %s\n",stu.name,stu.age,stu.score[0],stu.score[1],stu.addr)
}
fclose(fp1)
}
//
fprintf , fscanf, putw , getw , rewind , fseek 函数
这些函数的话我就不演示了 ,
这些函数基本都一对来使用,例如 fputc 和 fgetc 一起来用.
java是跨平台语言,在linux上读文件跟在windows上读文件是一样的 只是文件路径不一样,可以用File对象和FileInputSteam来读取。但要注意文件编码问题。\x0d\x0a如果有中文请做适当的编码转换,通常情况下Linux的默认字符编码为UTF-8编码方式,项目可以直接采用utf8编码方式 *** 作.用System.getProperty("file.encoding")可检查系统编码格式。可改 *** 作系统的文件系统编码,vi /etc/profile,在文件末尾加上\x0d\x0aexport LANG="zh_CN.GBK"\x0d\x0aexport LC_ALL="zh_CN.GBK"\x0d\x0a编码转换代码:new String(files[i].getName().getBytes("GBK"),"UTF-8")\x0d\x0a\x0d\x0a文件 *** 作的核心代码请参考下面代码:\x0d\x0a\x0d\x0aString path= "/home/"\x0d\x0apath= "/home/multiverse/Repository/PMEPGImport"\x0d\x0aFile file=new File(path)\x0d\x0aFile[] tempList = file.listFiles()\x0d\x0afor (int i = 0i 回答于 2022-12-11欢迎分享,转载请注明来源:内存溢出
评论列表(0条)