库函数 - 创建目录
int mkdir(char *dir, int mode)
功能:创建一个新目录。返回0表示成功,返回-1表示出错。
// 拷贝一个文件到另外一个地方
#include <stdio.h>
int main()
{
FILE *fp = NULL; //定义文件指针,定义指针时需要将指针指向空。
FILE *fq = NULL;
char ch;
fq = fopen("/root/c_code/test/t.c", "a"); //“a”表示以附加的方式打开,如果文件不存在就创建文件
fp = fopen("/etc/passwd", "r") ; //打开文件
while ((ch = fgetc(fp)) != EOF) // fgetc和fputc拷贝
{
fputc(ch, fq);
}
fclose(fp); // 关闭文件
fclose(fq);
fp = NULL; // 将指针指向空,否则仍然指向原打开文件位置
fq = NULL;
return 0;
}
问题:如何实现文件名输入方式拷贝,即通用模式,当需要拷贝的时候,输入源文件名和目的文件名即可?
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *ffrom = NULL;
FILE *fto = NULL;
char ch;
if (argc < 3) // pop the error for less source or target file.
{
perror("Please input the source file and target file.\n");
}
ffrom = fopen(argv[1], "r") ;
fto = fopen(argv[2], "a");
while ((ch = fgetc(ffrom)) != EOF)
{
fputc(ch, fto);
}
fclose(ffrom); // close FILE pointer
fclose(fto);
ffrom = NULL; // point to NULL, otherwise it will still point to source file.
fto = NULL;
return 0;
}
格式化读fscanf: int fscanf(FILE *stream, char *format, [argument...])
#include <stdio.h>
int main(){
int i;
fscanf(stdin, "%d", &i); //格式化读
printf("the i is %d.\n", i);
}
注意:fscanf读以空格或者回车作为结束符,例如输入"2 5",此时只读取2
格式化写fprintf:int fprintf(FILE *stream, char *format, [argument...])
#include <stdio.h>
#define SOURCE_FILE "/root/c_code/test/t.c" //宏定义文件
int main(){
int a = 1;
char c = '\n';
char s[] = "this is a string.";
FILE *fp = NULL;
fp = fopen(SOURCE_FILE, "a"); //打开文件,并用文件指针指向它
fprintf(fp, "%s%c", s, c); //写入s字符串和c字符
fprintf(fp, "%d\n", a); //写入a数字
fclose(fp); //关闭文件指针
fp = NULL;
}
