以下是c语言对文件的操作。
file2.c 、file3.c。open的第一个传参为文件名,是字符串格式,我们需要将字符串(如file)与数字(1/2/3)连接起来。问题即转化为
2、如何把字符串与整数连接起来?
#include<stdio.h>
int main(){
char filename[80];
printf("The file to delete:");
gets(filename);
if( remove(filename) == 0 )
printf("Removed %s.", filename);
else
perror("remove");
}
需要注意的是,gets()函数有潜在的危害,即当输入字符串的长度大于缓冲区长度时,并不会截断,原样输出读入的字符串,造成程序崩溃。可用fgets()代替。此部分参考
C语言remove()函数:删除文件或目录
stat原型:int stat(const char *file_name, struct stat *buf);
说明:通过文件名filename获取文件信息,并保存在buf所指的结构体stat中stat("test.txt",&buf);
printf("1.link=%d\n",buf.st_nlink);//测试链接数
举例1:
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
void main( void )
{
struct stat buf;
int result;
//获得文件状态信息
result =stat( "/home/", &buf );
//显示文件状态信息
if( result != 0 )
perror( "显示文件状态信息出错" );//并提示出错的原因,如No such file or directory(无此文件或索引)
else
{
printf("文件大小: %d", buf.st_size);
printf("文件创建时间: %s", ctime(&buf.st_ctime));
printf("访问日期: %s", ctime(&buf.st_atime));
printf("最后修改日期: %s", ctime(&buf.st_mtime));
}
}
举例2: Linux下 C语言实现遍历指定目录下指定格式的文件
int size = strlen(dirp->d_name);
if(size<5) //如果是.wav文件,长度至少是5
continue;
if(strcmp( ( dirp->d_name + (size - 4) ) , ".mp3") != 0) //只存取.mp3扩展名的文件名
continue;
fputs(dirp->d_name,fp);
fputs(" ",fp); // 在一个filename结束之后,写入空格,方便脚本读取,进程转换操作
用法: ln aa bb
ln -s aa cc
给aa创建一个bb的硬链接和cc的软链接。可通过ls -l查看。
关于link和unlink、close等API详见 Linux中link,unlink,close,fclose函数详解
简而言之,link在创建硬链接的会创建文件,而unlink在删除硬链接的同时会删除文件。文件通过unlink删除后fd还在,需要close来关闭。