我有一个包含文件夹名称的文本文件。我想通过 Ubuntu 终端读取该文本文件的上下文并使用该名称创建一个文件夹(写在 txt 文件中)。我不知道该怎么做,我有制作了一个名为“in.txt”的文件,它的上下文是“name”,我尝试了下面的c代码:
#include <stdio.h>
int main(){
FILE *fopen (const char in.txt, const char r+);
}
我应该在终端写什么?
假设您有一个名为的文本文件in.txt
,其中包含
Rambo
Johnny
Jacky
Hulk
接下来,您需要从文件中逐字读取,为此您可以使用fscanf()
. 读取单词后,您需要使用该单词名称创建一个文件夹。创建文件夹的命令是mkdir
. 接下来,您需要mkdir
从文件中执行您使用的文件system()
或execlp()
。
这是简单的C程序
int main(){
FILE *fp = fopen ("in.txt", "r");
if(fp == NULL) {
/* write some message that file is not present */
return 0;
}
char buf[100];
while(fscanf(fp,"%s",buf) > 0) {
/* buf contains each word of file */
/* now create that folder use execlp */
if(fork() ==0 )
execlp("/bin/mkdir","mkdir",buf,NULL); /* this will create folder with name available in file */
else
;
}
fclose(fp);
return 0;
}
请注意,mkdir
如果目录已存在,则失败。像创建文件夹gcc -Wall test.c
一样编译并执行它./a.out
。
编辑:相同如果您想使用open()
系统调用,则不会有任何系统调用逐字读取,因此您需要进行字符串操作。
int main(int argc, char *argv[]) {
int inputfd = open("in.txt",O_RDONLY);
perror("open");
if (inputfd == -1) {
exit(EXIT_FAILURE);
}
/* first find the size of file */
int pos = lseek(inputfd,0,2);
printf("pos = %d \n",pos);
/* againg make inputfd to point to beginning */
lseek(inputfd,0,0);
/*allocate memory equal to size of file, not random 1024 bytes */
char *buf = malloc(pos);
read(inputfd,buf,pos);/* read will read whole file data at a time */
/* you need to find the words from the buf, bcz buf contain whole data not one word */
char cmd[50];/* buffer to store folder name */
for(int row = 0,index = 0; buf[row]; row++) {
if(buf[row]!=' ' && buf[row]!='\n') {
cmd[index] = buf[row];
index++;
continue;
}
else {
cmd[index] = '\0';
index = 0;/* for next word, it should start from cmd[0] */
if(fork() == 0 )
execlp("/bin/mkdir","mkdir",cmd,NULL);
else ;
}
}
close(inputfd);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句