The c language gets the implementation code of windows and linux for the current working path

  • 2020-05-30 20:47:20
  • OfStack

Linux

The function name: getcwd
Power: gets the current working directory
Usage: char *getcwd(char *buf, size_t size);

Function description: getcwd() copies the absolute path of the current working directory to the memory space referred to by parameter buf, and parameter size is the size of buf. When calling this function, buf refers to a large enough memory space, if the absolute path of the working directory string length exceeds the size of the parameter size, the return value NULL, errno is ERANGE. If the parameter buf is NULL, getcwd() will automatically configure memory according to the size of the parameter size (using malloc()). If the parameter size is also 0, getcwd() will determine the size of the configured memory according to the extent of the string in the absolute path of the working directory.
Return value: copies the result to the memory space indicated by the parameter buf on success, or returns a pointer to the automatically configured string. Failure returns NULL, error code in errno.

Application:


#include <stdio.h>   
 #include <unistd.h>  
 
main()  
 {  
   char buf[80];  
   getcwd(buf,sizeof(buf));  
   printf("current working directory: %s\n", buf);  
 }

linux C gets the current working directory method 2


#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
	char buffer[1024] ;

	// Gets the current working directory, note: the length must be greater than the length of the working directory plus 1
	char *p = getcwd(buffer , 40);
	char *dir = NULL;

	printf("buffer:%s  p:%s size:%d \n" , buffer , p , strlen(buffer));
	// Gets the name of the current working directory 
	dir = (char *)get_current_dir_name();
	printf("dir:%s \n" , dir);

	char *twd = NULL ; 		
	twd = getwd(buffer);	
	printf("buffer:%s  twd:%s \n" , buffer , twd);
	return 0 ; 
}

Operation results:
buffer: p:(null) size:0
dir: / mnt/sdb1 / yangyx/system system programming interface and sound card/file directory
buffer: / mnt/sdb1 / yangyx/system system programming/file directory interface and sound card twd: / mnt sdb1 yangyx/system system programming interface and sound card/file directory

Windows directory operation

1. Get the current working directory


char* _getcwd( char *buffer, int maxlen );
//  work   can  :  Get the current working directory .
//  The header file  : #include <direct.h>
//  The return value  :  Successful return to point buffer the pointer
//      Failure to return NULL And set up errno For the following 3 A value of 1:
//      ENODEV  Without this equipment 
//      ENOMEM  Out of memory 
//      ERANGE  Results out of range 
//  note   meaning  :  When the first 1 The parameters for  NULL  when ,  The first 2 A parameter  maxlen  Invalid length setting , And function 
//      use  malloc  Allocate enough memory ,  The return value of the function needs to be passed to  free()  Function to 
//      Free memory .  When the first 1 Is not  NULL  when ,maxlen  The specified length is not enough to return the function 
//      wrong , Set up the errno for ERANGE

2. Change the current working directory


int _chdir( const char *dirname );
//  work   can  :  Change the current working directory .
//  The header file  : #include <direct.h>
//  The return value  :  Successfully returns 0
//      Failure to return -1 And set up errno The following :
//      ENOENT  The path does not exist 

3. File traversal (search)


long _findfirst( char *filespec, struct _finddata_t *fileinfo );
//  work   can  :  To provide with filespec Specifies the size of the entry for a generic match 1 A file . Usually for subsequent use _findnext letter 
//      Number of subsequent use to complete a generic file traversal .
//  The header file  : #include <io.h>
//  ginseng   The number  : filespec -  Object file specification , You can include wildcards 
//     fileinfo -  File information buffer
//  The return value  :  Successful return only 1 The search handle 
//      Returns the error -1, And set up errno For the following values :
//      ENOENT  The generic does not match 
//      EINVAL  Invalid file name 
//  note   meaning  : _finddata_t  instructions 

struct _finddata_t
{
  unsigned attrib;
  time_t time_create;
  time_t time_access;
  time_t time_write;
  _fsize_t size;
  char name[_MAX_FNAME];
};
//  Among them   : 
// unsigned atrrib :  Where file properties are stored. It is stored 1 a unsigned Cell used to represent a file 
//            Properties. File properties are represented in bits, mainly as follows 1 Some: _A_ARCH (file), 
//           _A_HIDDEN (hide), _A_NORMAL (normal), _A_RDONLY (read only), 
//           _A_SUBDIR (folder), _A_SYSTEM (system). These are all in <io.h> In the 
//            Define the macro, can be used directly, but its own meaning is actually 1 Two unsigned integers 
//           Only the integer should be 2 Omega to some power of theta, so that there's only one 1 Bit is 1 And the other 
//            Bit is 0 ). Since it's a bit representation, then when 1 When a file has more than one property, it tends to be 
//            The synthesis of several properties is obtained by means of bits or bits. Such as read-only + hidden + System properties, 
//            Should be as follows: _A_HIDDEN | _A_RDONLY |_A_SYSTEM  . 
// time_t time_create Here: time_t is 1 Is used to store the file creation time. 
// time_t time_access:  File the last 1 The time of the last interview. 
// time_t time_write :  File the last 1 The time that was last modified. 
// _fsize_t size   :  Size of file. Here, _fsize_t It should be equivalent to unsigned Integer, which means 
//            The number of bytes in a file. 
// char name[_MAX_FNAME] : the name of the file. Here, _MAX_FNAME is 1 It's a macro. It's a macro <stdlib.h> head 
//             Is defined in a file and represents the maximum length of the file name. 

int _findnext( long handle, struct _finddata_t *fileinfo );
//  work   can  :  According to the previous _findfirst In the generic rule, look it up 1 A file that conforms to the generic and is based on it 
//      Modify the fileinfo The values in the 
//  The header file  : #include <io.h>
//  ginseng   The number  : long handle -  Handle to the search ( Usually by close in front of it _findfirst() return )
//     fileinfo  -  File information buffer
//  The return value  :  Successfully returns 0
//      Returns the error -1, And set up errno For the following values :
//      ENOENT  There are no more files that conform to this generic 

int _findclose( long handle );
//  work   can  :  Close the search handle and release the corresponding resource 
//  The header file  : #include <io.h>
//  ginseng   The number  : long handle -  Handle to the search ( Usually by close in front of it _findfirst() return )
//  The return value  :  Successfully returns 0
//      Returns the error -1, And set up errno For the following values :
//      ENOENT  There are no more files that conform to this generic 

4. Create a directory


int _mkdir( const char *dirname );
//  work   can  :  create 1 A new directory , Directory called dirname.
//  The header file  : #include <direct.h>
//  The return value  :  Successfully returns 0
//      Failure to return -1 And set up errno For the following 3 A value of 1:
//      EACCESS  Permission not allowed 
//      EEXIST   The directory already exists 
//      ENOENT   No such file or directory 

5. Delete the directory


int _rmdir( const char *dirname );
//  work   can  :  Delete the named dirname The directory where the .
//  The header file  : #include <direct.h>
//  The return value  :  Successfully returns 0
//      Failure to return -1 And set up errno For the following 3 A value of 1:
//      EACCESS  :  Permission not allowed 
//      ENOTEMPTY : dirname Not a folder ; Or the folder is not empty ; or 
//             those dirname For the current working folder ; or dirname
//             For when the root folder ;
//      ENOENT  :  No such file or directory 

6. Other operations


int _access( const char *path, int mode );
//  work   can  :  The determination of the file / Directory access rights .
//  The header file  : #include <io.h>
//  ginseng   The number  : path -  File or directory 
//     mode -  Permissions set , Its value is as follows :
//          00 Existence only 
//          02 Write permission 
//          04 Read permission 
//          06 Read and write permission

int _chdrive( int drive );
//  work   can  :  Change the current working drive .
//  The header file  : #include <direct.h>
//  The return value  :  Successfully returns 0
//      Failure to return -1
//  note   Interpretation of the  :  Parameters that 
//      drive =1 : A disc 
//      drive =2 : B disc 
//      drive =3 : C disc  ...

char* _getdcwd( int drive, char *buffer, int maxlen );
//  work   can  :  Gets the current working path of the specified drive .
//  The header file  : #include <direct.h>
//  The return value  :  Successful return to point buffer the pointer
//      Failure to return NULL And set up errno For the following 3 A value of 1:
//      ENODEV  Without this equipment 
//      ENOMEM  Out of memory 
//      ERANGE  Results out of range 
//  note   meaning  :  When the first 1 The parameters for  NULL  when , This function is set errno for ERANGE

Testing:


//  work   can  :  Printed catalogue path With the model chRE Match all documents clearly 
//  Lose,   Into the  : path -  The directory to print 
//     chRE -  A matching regular expression is required 
static void printDir( const char* path, const char* chRE )
{
  char* chCurPath = getcwd( NULL, 0);       //  Current working directory 
  printf("current work path: %s\n", chCurPath );
  
  
  int ret = _chdir( path );
  if ( ret < 0 )
  {
    perror( path );
  }


  char* newPath = getcwd( NULL, 0 );
  printf("new work path: %s\n", newPath);
  free(newPath);


  struct _finddata_t data;
  long hnd = _findfirst( chRE, &data );  //  Look for file names and regular expressions chRE Match the first 1 A file 
                       //  Return only 1 The search handle 
  
  if ( hnd < 0 )
  {
    perror( chRE );
  }
  
  int nRet = (hnd <0 ) ? -1 : 1;
  
  while ( nRet >= 0 )
  {
    if ( data.attrib == _A_SUBDIR ) //  If it's a directory 
      printf("  [%s]*\n", data.name );
    else
      printf("  [%s]\n", data.name );
    
    nRet = _findnext( hnd, &data );
  }
  
  _findclose( hnd );   //  Close the current handle 


  chdir( chCurPath);     //  Switch back to the previous working directory 
  free( chCurPath );
}

The C language gets the current working path and the.exe path

I was having trouble getting the.exe executable path today. It worked out at last.
When I started with GetCurrentDirectory (or _getcwd), I found that it only got me the current working path. If your code operates on files in other folders, you get a different result. And I want to get the path where the current exe executable is located.
It turned out to be this:
The path of my exe file is:
C:\Users\Jovan \ Yang\Desktop\ paper code \UnAPK & Extract all API\Debug\xxx.exe


char exeFullPath[MAX_PATH]={0};
GetModuleFileName(NULL,exeFullPath,MAX_PATH);// Get program module .exe The full path 
// Next, put the xxx.exe The file name is removed, as follows 4 A: 
*strrchr( exeFullPath, '\\') = 0;// get C:\Users\Jovan Yang\Desktop\ Paper code \UnAPK&Extract all API\Debug
strrchr( exeFullPath, '\\')[0]= 0;// Also get C:\Users\Jovan Yang\Desktop\ Paper code \UnAPK&Extract all API\Debug
*(strrchr( exeFullPath, '\\')+1) = 0;// get C:\Users\Jovan Yang\Desktop\ Paper code \UnAPK&Extract all API\Debug\
strrchr( exeFullPath, '\\')[1]= 0;// Also get C:\Users\Jovan Yang\Desktop\ Paper code \UnAPK&Extract all API\Debug\

All right, that's it. More search still can solve. That's the end of this article, which is basically a very detailed introduction to common operations in windows.


Related articles: