首页 > 学院 > 开发设计 > 正文

文件名称与基本文件读取

2019-11-08 02:40:15
字体:
来源:转载
供稿:网友

文件夹或文件删除与创建

remove(argv[2]);mkdir(argv[2], S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);// here is the same to the linux command.// 头文件 <unistd.h>

绝对路径的文件名与路径名称

char *dir = dirname("/home/users/PRoject/nnwork");// dir is reference to "/home/users/project"char *filename = basename("/home/users/project/nnwork");// filename is reference to "nnwork"// 头文件 <libgen.h> 相关

文件读取

struct stat buf;stat(input, &buf);char *id_string = NULL;id_string = new char [buf.st_size];/* * 头文件 <sys/types.h> <sys/stat.h> */

代码

#include <string.h>#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <libgen.h>#include <unistd.h>#include <iostream>int process_one_file(char *input, char *output){ if (NULL == input || NULL == output) { printf("input or output wrong/n"); return -1; } struct stat buf; stat(input, &buf); char *id_string = NULL; id_string = new char [buf.st_size]; // input FILE *fp = fopen(input, "rb"); if (NULL == fp) { printf("open input [file:%s] wrong/n", input); return -1; } fread(id_string, sizeof(char), buf.st_size, fp); fclose(fp); // output fp = fopen(output, "wb"); if (NULL == fp) { printf("open output [file:%s] wrong/n", output); return -1; } fwrite(id_string, sizeof(char), buf.st_size, fp); fclose(fp); delete [] id_string; return 0;}int main(int argc, char *argv[]){ if (argc < 3) { printf("usage: %s input_list out_dir/n", argv[0]); exit(-1); } remove(argv[2]); mkdir(argv[2], S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); // here is the same to the linux command. FILE *fp = fopen(argv[1], "rt"); const int LEN = 1024; char line[LEN]; char input[LEN]; char output[LEN]; ///// char filename[LEN]; char *p; int len = 0; while (fgets(line, LEN, fp)) { len = strlen(line); while ((line[len-1] == '/n' || line[len-1] == '/t' || line[len-1] == ' ') && len > 0) line[--len] = 0; if (len < 1) continue; snprintf(input, LEN, "%s", line); input[LEN-1] = 0; //filename = basename(input); //snprintf(output, LEN, "%s/%s", argv[2], filename); p = basename(input); // here is the same to the linux cammand basename, // and the dir name is dirname(char *) snprintf(output, LEN, "%s/%s", argv[2], p); output[LEN-1] = 0; //free(filename); printf("input : %s/n", input); printf("output : %s/n", output); process_one_file(input, output); } return 0;}

看例子里面,基本都讲到了。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表