Create a directory - c

I am trying to create a directory using the following code. It compiles, but it does not create a directory. Any suggestions?
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
int main(void)
{
const char base[] = "filename";
char filename [ FILENAME_MAX ];
int number = 42;
sprintf(filename, "%s/%d", base, number);
printf("filename = \"%s\"\n", filename);
mkdir (filename, S_IRWXU);
return 0;
}

Does the "filename" directory already exist? mkdir() will only create one directory at a time; if the parent directory doesn't exist either, you'll have to create it separately, first.

Most probably it fails to create directory because you are trying to create a nested directory and its parent does not exist. mkdir cannot create directories recursively. But you can only guess unless you properly check return codes and errors in your program.

Related

how to create folders using mkdir in c?

I'm trying to create a folder using mkdir in C but it wont't work
the code won't create the folders
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
int main (){
char chemin[256];
char name[20];
//char fichier[100];
// FILE *fp;
strcpy(chemin,"/home/Deva/Documents/prog/C/la/sds");
mkdir(chemin,0755);
if (mkdir(chemin,0755)==-1){
printf("\nERROR\n");
} else { printf("fichier creer"); }
}
You have to create the intermediate directories first: e.g. you must create /home/Deva before creating /home/Deva/Documents, etc.
you are passing PATH not just directory name.
so please check below post would help
Recursive mkdir() system call on Unix
2 things:
1) You need to create the intermediate directories first.
2) You cannot create a directory twice, which you do here:
mkdir(chemin,0755);
if (mkdir(chemin,0755)==-1){

GCC fatal error: quit.h no such file or directory

I am learning C for an operating systems course and have just finished writing this program as per the textbook instructions:
#include <dirent.h>
#include <stdio.h>
#include "quit.h"
int main(int argc, char **argv) {
DIR *dir;
struct dirent *direntry;
arg_check(2, argc, "Specify a directory\n", 1);
if ( (dir = opendir(argv[1])) == NULL)
quit("opendir", 1);
while ((direntry = readdir(dir)) != NULL)
printf("%10d %s\n", direntry->d_ino, direntry->d_name);
closedir(dir);
exit(0);
}
This code is exactly copied from the textbook, but quit.h appears to be causing the compile to file. I have tried switching "quit.h" to , and "quit", but none of these have worked, and I cannot find other questions about this specific issue.
include "quit.h"
The word #include (with its hash # prefix) means that a file has to be read in; the content of that file (quit.h in this case) is processed exactly as if it was typed inside the program. Suppose you have a file name "test.h" which contains the single line
// this is a test
if you a have a program like this:
#include "test.h"
int main(int argc, char **argv)
...
the compiler processes (sees) exactly these lines:
// this is a test
int main(int argc, char **argv)
...
The file name specified after #include can be enclosed with angles or quotes. Conventionally, if angles are used, like
#include <stdio.h>
this means that the file (stdio.h in this case) is some system or standard file or so - in other simple words, someone else has written that file for you. If quotes are used, instead, the file specified is considered somehow part of the program you are compiling. Your quit.h seems like this. So you must have a file named quit.h. If you change that "quit.h" to "quit", a file named quit must be present in the same directory of the file you are compiling. (Actually things are more complicated, but don't mind it for now). Read your book, somewhere it should explain what is that file "quit.h".

lstat returning <0

Basically, this should be a simple piece of code that opens a directory stream and looks for symbolic links. Whenever a symbolic link is found, it should print ("Symbolic link found");
However, the lstat(dirp->d_name,&bufcall always returns a value < 0, and I don't know why.
I created the two symbolic link opening the file folder, opening a terminal window inside the folder and running
ln -s ciao.txt link1 and
ln -s ciao2.txt link2
I know I should call closedir() later in my code, please don't care about this.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
void main (int argc, char* argv[])
{
char buffer[100],dir[100];
struct stat buf;
int x;
DIR *dp;
struct dirent *dirp;
if((dp=opendir(argv[1]))==NULL)
{
printf("\nError opening directory stream, now exiting...\n");
exit(-1);
}
while((dirp=readdir(dp))!=NULL)
{
lstat(dirp->d_name,&buf);
if(S_ISLNK(buf.st_mode))
printf("\n%s Is a symbolic link\n",dirp->d_name);
else
printf("\n%s Is not a symbolic link\n",dirp->d_name);
}
}
Some help would be appreciated. Thanks.
d_name is the file name in the directory, not a full path name. You must eather chdir into the directory you are looking at, or construct full path names for the files.
The simplest solution is to add this line just before your while loop:
chdir(argv[1]);

mkdir -p equivalent in C that creates nested directories recursively

I want to create a new directory inside a new directory. Something like this:
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
int main() {
const char * path = "/home/abc/testabc1/testabc2" ;
mode_t mode = 0777;
if (mkdir(path, mode) == -1) {
// printf("Error occurred : %s ", strerror(errno));
perror("abc");
}
else {
printf("Directory created\n");
}
}
When I do this I get this error:
abc: No such file or directory
If I remove testabc2 then I am able to create the directory with success. Why so ?
You can only create directories in existing directories. If you want to do the equivalent of mkdir -p you have to do the same thing it does, namely create one directory after another from the top of the path down.
In your case, that means mkdir of /home/abc/testabc1 before mkdir of /home/abc/testabc1/testabc2.
Your error message is also misleading since perror("abc"); will prepend any error with "abc:". It has nothing to do with the directory "abc".

Why is the file size repeating itself?

I'm trying to list files and their sizes in "first" folder but I am getting weird repetition of every two files.
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
struct dirent *dirPtr;
struct stat st;
void main()
{
DIR * dirp;
if((dirp=opendir("first"))==NULL)
{
printf("There has been an error");
}
while(dirPtr=readdir(dirp))
{
printf("%s - ", dirPtr->d_name);
stat(dirPtr->d_name, &st);
printf(" file size: %lu\n", st.st_size);
}
closedir(dirp);
}
This is my output:
Does anyone know why this is happening?
For starters, you should probably check the return result from "stat()", and print an error # (instead of file size) if stat() fails.
Also: "opendir()" is reading files from some arbitrary directory.
Q: Does "dirPtr->d_name" contain a full filepath ... or just a filename? In other words, are you trying to "stat()" from the wrong directory?
You are basically calling stat("test.c", &st). How is stat supposed to know what directory test.c is in? I don't think it can.
I think you should try doing stat("./first/test.c", &st) or stat("/full/path/to/first/test.c", &st). Better yet, you should find some function like stat that takes a struct dirent as the argument, so you don't have to worry about concatenating strings.
I'll see if there is a such a function and edit my answer if I find one.
Every directory has at least two entries, the current directory - a single dot . - and the parent directory - two dots ..

Resources