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 一起来用.
Linux c语言可以使用系统提供的mkdir函数来创建文件夹。
1、函数原型
int mkdir(const char *path, mode_t mode)
2、参数说明:
path是目录名mode是目录权限
3、需要头文件
#include <sys/stat.h>4、示例
//添加mkdir函数声明头文件#include <sys/stat.h>
#include <sys/types.h>
int main() //主函数
{
//直接调用mkdir函数
//建立一个名为zhidao的文件夹
//权限为0777,即拥有者权限为读、写、执行
//拥有者所在组的权限为读、写、执行
//其它用户的权限为读、写、执行
mkdir("zhidao",0777)
return 0
}
说明:函数调用试图建立777权限的文件夹,但是在实际程序执行时,还需要考虑umask值,最终才会得到实际的权限。
5、执行效果如下图所示
说明:t.c是源码文件,有gcc进行编译,-o是gcc的参数,有于指明编译后输出的文件,t为源码经gcc编译后生成的可执行文件。./t是执行当前目录下的生成的可执行文件t。
示例教程:
1. 编写代码
在linux下面使用命令创建main.c文件
vim main.cmain.c代码:
#include <stdio.h>#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define MAX 50
int main()
{
int fd
char buf[MAX]
fd = open("1.txt",O_WRONLY|O_CREAT|O_APPEND)
if(fd == -1)
{
printf("文件创建失败")
return -1
}
printf("请输入要写入的句子:")
fgets(buf,MAX,stdin)
write(fd,buf,MAX)
printf("写入成功\n")
return 0
}
2.编译源程序
gcc main.c -o main结果在此路劲下会出现main源程序
3.运行源程序
查看文件是否创建且写入成功
完成
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)