open different file using C programming - c

Hello ever one I want to ask a question about file opening.I want to write a program in which I will give a path to my main folder.main folder can contain files and and other folders which in again contain other folders and files.I want to open all the file in the loop and do some manipulation on them also I want to open only specific file for example .c extended file.Is there a built in program or function that do that? or atleast is there a way through which I can check which files are there in the folder so that I can repeatedly open them
I am using C programming linux
Thanks

You can save yourself a lot of work and look at ftw() and nftw(). They will walk through directories and their entries , starting with the path you provide, and a call a callback function that you provide. In your callback you can check if the file is relevant for purpose and operate on it if it is.
Also glob() will save you some effort if you are going to be doing a lot of filename matching.

I am not aware of any built-in functions for what you want to do here. But you could use dirent.h.
int main(){
DIR *dir;
struct dirent *ent;
dir = opendir ("c:\\folder\\");
if (dir != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}
Here you can find even more examples.

opendir, readdir, closedir.
if dirent->d_type==DT_DIR, descend into it (recursion would help).
Take a look at the file name, figure out if you're interested.

Related

renaming, and moving files from a directory using c

i am working on a home made little program that is going to make my life a lot easier.
the idea is it looks at a directory, sees the file names in it, removes all certain character combinations and certain characters from the name of the files, then copies the newly named file to a separate folder, and deletes the original.
i can do most of that. what i dont know is how to load the file names into my program i can figure everything else out as i know how to manipulate strings in C and so on.
ive been looking for an easy to implement solution for a few days and found nothing.
tldr:
look at directory
load all file names
change all file names based on criteria
copy files to new directory.
i dont really know how to do step 1, 2, or 4.
i dont expect you guys to write the program for me, even a library and command suggestion would be great if there is one.
See a few related questions : How can I get the list of files in a directory using C or C++?
Read file names from a directory
And as stated on this page :
https://www.geeksforgeeks.org/c-program-list-files-sub-directories-directory/
Using the <dirent.h> module, doing so :
#include <stdio.h>
#include <dirent.h>
int main(void)
{
struct dirent *de; // Pointer for directory entry
// opendir() returns a pointer of DIR type.
DIR *dr = opendir(".");
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory" );
return 0;
}
// Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
// for readdir()
while ((de = readdir(dr)) != NULL)
printf("%s\n", de->d_name);
closedir(dr);
return 0;
}
Would allow you to see the files and directories inside a directory.
I think with this, you should be good.

Accessing a different drive in c

I want to scan a directory, checking for JPEG-files (i.e. the combination of the first few bytes) and copying them to another drive. I successfully tested that program and it screens documents. However, I cannot access a whole directory (e.g. my accidentally erased SD-Card in D:/).
Here is how I tried to access it:
// remember the path from the command line
char *path = argv[1];
// open the path (preferably "D:\" - which is my SD-Card ;))
FILE *inptr = fopen(path, "r");
if (inptr == NULL)
{
fprintf(stderr, "inputfile could not be read\n");
return 1;
}
The output is "inputfile could not be read" - which is why I am quite confident that the error is right there. Do I need to address a directory differently? E.g. by using a pointer to the first bit of the drive?
I am a beginner - so please be gentle while laughing. ;)
Thank you very much!
Marcel
'fopen()' cannot open an entire directory or drive, it can only open a specific path. However, there are ways to accomplish the task of listing all files in a directory. This answer already contains some pertinent information.
Since you can already open files,you could adapt the loop shown there to perform the operation.
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
if (/*Check whether file has the .jpg extension or another test*/)
{
// perform your copy operation on the file
}
}

Where to put files so C program can access them?

I'm trying to open files in a C program, but I am unsure where to place the files I want to open (as in which directory). Here is the code, but I really just need to know where to place the file I want to open with fopen().
FILE *fileptr;
fileptr = fopen("QuizQuestions.txt", "r");
if (fileptr == NULL) {
printf("Unable to open file.");
}
Any help is appreciated!
If you don't use an absolute pathname in your code, paths are interpreted relative to the working directory of the user when they run the program. So for your program, the user should put the file in their current directory.
The location of the program itself is irrelevant. If you want to get the location of the program, you see this question:
How do I find the location of the executable in C?
You can then concatenate the directory with the filename.
You need to keep files where source code file is placed.Otherwise, you need to give absolute path.

how to check if a file is in current directory in C?

How do I check if a file(input) is in the program's directory in C?
First I think I can just open the file, but I don't want user to see my other files by input something like ../important_dir/important_file, but maybe it's OK if the user do things like ./dir1/../file1. Which means, as long as the file is in current dir(no child dir), it's OK to open that.
Then I search around and found readdir, which can be used to lookup everything in current directory, but still, if current directory has a lot of files, it will be way too slow to lookup a filename every time getting a user input.
Is there any fast and secure way to do that?
I think realpath should do the work.
I'll post solution tomorrow if possible.
You can just use stat() to check for a file's status. It would return -1 if the file in question does not exist and set errno to ENOENT.
char filename[] = "myfile";
struct stat s = {0};
if (!(stat(filename, &s)
{
if (ENOENT == errno)
perror("file does not exist.");
}

How to open a text file that's not in the same folder?

Since C it's not a language I am used to program with, I don't know how to do this.
I have a project folder where I have all the .c and .h files and a conf folder under which there is a config.txt file to read. How can I open that?
FILE* fp = fopen("/conf/config.txt", "r");
if (fp != NULL)
{
//do stuff
}
else
printf("couldn't open file\n");
I keep getting the error message. Why?
Btw, this only have to work on windows, not linux.
Thanks.
The easy way is to use an absolute path...
my_file = fopen("/path/to/my/file.txt", "r");
Or you can use a relative path. If your executable is in /home/me/bin and your txt file is in /home/me/doc, then your relative path might be something like
my_file = fopen("../doc/my_file.txt", "r");
The important thing to remember in relative paths is that it is relative to the current working directory when the executable is run. So if you used the above relative path, but you were in your /tmp directory and you ran /home/me/bin/myprog, it would try to open /tmp/../doc/my_file.txt (or /doc/my_file.txt) which would probably not exist.
The more robust option would be to take the path to the file as an argument to the program, and pass that as the first argument to fopen. The simplest example would be to just use argv[1] from main's parameters, i.e.
int main(int argc, char **argv)
{
FILE *my_file = fopen(argv[1], "r");
/* ... */
return 0;
}
Of course, you'll want to put in error checking to verify that argc > 2, etc.
You're probably going to want to look into the dirent family of routines for directory traversal.
The location of your .c and .h files is not really the issue; the issue is the current working directory when you run your executable.
Can you not pass in the full path to the fopen() function?

Resources