parsing a path using a functoin called getfullpathname() in C? - c

Im begginer to C, currently have to learn C and Win32 API, and in my first project i need to get from the user a path name and a file name, then check if the file exists and delete it if the user wants to.
Im currently stuck at finding whether a file exists.
Im familiar with a solution that was shown in this site before (What's the best way to check if a file exists in C?) but I have been hinted/instructed to use a function called getfullpathname() in order to parse the strings and then checking if the file entered exists.
My problem is that all GetFullPathName does as far as i searched (tried to understand the MSDN and couple or more sites) is concatinating the working drive and directory onto the filename you've provided.
Am i missing something? Do i need to change the working directory to the path entered in order to concatinate the path and the name file or just pass to the function the path for it to parse it so i could be able to do the checking?
Do i need this function only for parsing the path or to concatinate the path string and the name string?
Could you provide me with the example of doing this first part of the project?
Thanks in advance.

concatinating the working drive and directory onto the filename you've provided.
Not a simple concatenating, This function does not check if the file exists, but just parse the relative path of the file(no matter whether the file exists) to the absolute path. The first parameter of Function GetFullPathName is relative path of the file you need to put in. If the file is located under the current working directory, you only need to send the filename to the function call. If the file is located in the upper path, then you can send ../filename, the function will parse it to an absolute file path.
You could use GetShortPathName. If the file does not exist, the call will fail, and return 0.

Hmmm, According to my practice
Assuming that the file is in the current working directory, GetFullPathName sounds like a good idea. It accepts a file name and converts it to a full path by presetting the current working directory.
Note: The API returns a path regardless of whether the file exists
in the working directory or not; it only uses the file name you
provide and prepares the current working directory in advance.
DEMO1:
#include <windows.h>
int main()
{
char filename[] = "test.txt";
char fullFilename[MAX_PATH];
GetFullPathName(filename, MAX_PATH, fullFilename, nullptr);
MessageBox(NULL, fullFilename, "DEBUG", MB_OK);
}
Debug Result:
In fact, there is no test. txt text document at all.
So you can do it in the following way
DEMO2:
#include <windows.h>
int main()
{
char lpszPath[] = "..\\Project20";
long length = 0;
TCHAR* buffer = NULL;
buffer = new TCHAR[length];
length = GetShortPathName(lpszPath, buffer, length);
if (length == 0)
{
MessageBox(NULL, "ERROR", "DEBUG", MB_OK);
}
else
{
MessageBox(NULL, "SUCCESS", "DEBUG", MB_OK);
}
delete[] buffer;
return 0;
}
Judgment of the existence of documents through ERROR and SUCCESS

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.

Creating a file using fopen()

I am just creating a basic file handling program.
the code is this:
#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
printf("Error",);
}
fclose(p);
}
This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success.
I am using Windows 7 and compiler is Dev C++ version 5
Change the mode argument in fopen(const char *filename, const char *mode) from:
p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0) // ^
To this:
p=fopen("D:\\TENLINES.TXT","w");//this will create a file for writing.
if(p==NULL) // ^ //If the file already exists, it will write over
//existing data.
If you want to add content to an existing file, you can use "a+" for the open mode.
See fopen() (for more open modes, and additional information about the fopen family of functions)
According to tutorial, fopen returns NULL when error occurs. Therefore, you should check if p equals NULL.
Also, in printf("Error",);, omit the comma after string.
Yes you should open the file in write mode.
Which creates the file . Read mode is only to read content
or else you can use "r+" for both read and write.
You should be able to open the file, but you need to make it first. Make a txt document with the name res.txt. It should be able to write your result into the text document.
<?php
$result = $variable1 . $variable2 "=" .$res ."";
echo $result;
$myfile = fopen("res.txt", "a+") or die("nope");
fwrite($myfile, $result);
fclose($myfile)
?>
fopen()
Syntax:
FILE *fp;
fp=fopen(“data.txt”,”r”);
if(fp!=NULL){
//file operations
}
It is necessary to write FILE in the uppercase. The function fopen() will open a file “data.txt”
in read mode.
The fopen() performs the following important task.
It searches the disk for opening the file.
In case the file exists, it loads the file from the disk into memory. If the file is found with huge contents then it loads the file part by part.
If the file does not exist this function returns a NULL. NULL is a macro defined character in the header file “stdio.h”. This indicates that it is unable to open file. There may be following reasons for failure of fopen() functions.
a.When the file is in protected or hidden mode.
b.The file may be used by another program.
It locates a character pointer, which points the first cha
racter of the file. Whenever a file is
opened the character pointer points to the first character of the file

Even after providing proper path in the program , I can not open the file in Visual C++

I have written a simple C code in visual C++
I am planning to open a text file for reading , but whenever i enter path it shows "unable to open the file".
then i hardcoded the path in the program itself. still same error , can anyone tell me what I am doing worng ? or where I wil have to copy paste that file so that i can open it in visual c++ through my code ?
here is my code :
#include<stdio.h>
#include<conio.h>
int main(){
FILE *p;
char file1[20];
char ch,i;
printf("\nEnter the source file name to be copied:");
gets(file1);
p=fopen(file1,"r"); // I have tried changing it with actual path to the file
if(p==NULL)
{
printf("cannot open %s",file1);getch();
exit(0);
}
while((i=getc(q))!=EOF)
printf("%c",i);
fclose(p);
return 0;
}
Save one file in your directory where you have saved the program.
And try it typing the perfect full name of the file including format of the file.
Your code seems error free.
When you're telling directory during execution use // only dont use / otherwise it will show you error and file won't open.
it worked after Entering double back slash "\\" instead of single back slash after the Drive name (example "c:\\") for the path to the file.

_findfirst failure with .. path

Why _findfirst returns -1 with ..\*.txt search pattern
struct _finddata_t c_file;
hFile = _findfirst("..\\*.txt", &c_file);
But processes ..\* correctly?
_findfirst works correctly when passed "..\\*.txt". The fact that it returns -1 indicates that there are no text files in the directory above your working directory.
Our comments:
Are there any txt files in the current working directory of your process? – H2CO3
there are no txt files – Chesnokov Yuriy
That's why. From the documentation:
Provide information about the first instance of a file name that matches the file specified in the filespec argument.
No surprise, no magic.

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.");
}

Resources