VC++, verifier l'existence d'un fichier et sa taille ?

VC++, verifier l'existence d'un fichier et sa taille ? - Programmation

Marsh Posté le 05-06-2001 à 16:14:39    

j'aimerais vérifier l'existance d'un fichier et la taille de ce fichier en bits (doit être > 0)
 Je ne pense pas que c'est très dur mais je ne trouve pas la fonction qui permet de faire ça.  
 
merci à tous !

Reply

Marsh Posté le 05-06-2001 à 16:14:39   

Reply

Marsh Posté le 05-06-2001 à 16:23:53    

Quelque chose comme
 
 DWORD   dwSize;
 HANDLE   hFile;
 
 hFile = CreateFile(szFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 if (hFile == INVALID_HANDLE_VALUE)
 {
   MessageBox(hWndParent, "Erreur Opening File", szFileName, MB_OK);
   return NULL;
 }
 // Quelle taille a le fichier ?
 dwSize = GetFileSize(hFile, NULL);
 
fermeture plus tard ...
 
En 16 bits, il y a OpenFile();

Reply

Marsh Posté le 05-06-2001 à 16:27:18    

CreateFile va-t-il "détruire" mon fichier s'il existe ?
j'ai besoin de savoir s'il existe pour vérifier le bon déroulement d'une procedure, non pas pour l'ouvrir. J'aurais aimé éviter l'ouverture du fichier jsute pour ça !
En plus, je ne veux pas le créer s'il ne l'a pas été.

 

[edit]--Message édité par Moustaaki--[/edit]

Reply

Marsh Posté le 06-06-2001 à 10:33:53    

Quand on ouvre un fichier en lecture, ou il existe, ou il n'existe pas.
S'il existe, pas de pb, on l'ouvre (faut le fermer ensuite). Tant qu'on ne lit pas, on ne sait même pas ce qu'il y a dedans.
S'il n'existe pas, il y a une erreur d'accés (car on veut ouvrir un fantôme).
 
Si on l'ouvre en écriture, il va l'écraser si on écrit ou (sans doute) le remettre à zéro si on le referme.
 
Un test sur un fichier quelconque sans importance permet de se rendre compte du résultat... Expérimentons, seul moyen de se rendre compte.
 
Pb potentiel : on peut avoir une erreur en ouverture (ou seulement en lecture, sais plus très bien) quand le fichier existe mais est "monopolysé" par un autre programme : genre QuickView (Word aussi me semble-t-il). On ne peut pas y accéder. L'erreur est détectable, mais ai pas les infos sous le coude.

Reply

Marsh Posté le 06-06-2001 à 10:52:05    

euhh  
et pourquoi tout simplement
ifstream l_file(nomFichier,ios::in)
if (l_file)
{
//verification de la taille
  l_file. (?) // a toi de trouver la methode :)
}
else
{//ouverture impossible
}
 
nan?
fk

 

[edit]--Message édité par frenchKISS--[/edit]

Reply

Marsh Posté le 06-06-2001 à 11:42:30    

il existe aussi une fonction du genre :
  FindFirstFile qui marche tres bien et qui est faite pour ca !!!
 
elle retourne en plus si le fichier est trouvé, le nom, les dates, la taille, ....

Reply

Marsh Posté le 06-06-2001 à 12:04:37    

Sous Windows, il y a des clones de stat, la fonction qu'un unixien utiliserait pour ce genre de probleme.
 
Selon ta version de Windows, il y a _stat, _wstat, _stati64 ou _wstati64 qui sont implementes sous windows.
int _stat( const char *path, struct _stat *buffer );
__int64 _stati64( const char *path, struct _stat *buffer );
int _wstat( const wchar_t *path, struct _stat *buffer );
__int64 _wstati64( const wchar_t *path, struct _stat *buffer );
 
Return Value
Each of these functions returns 0 if the file-status information is obtained. A return value of –1 indicates an error, in which case errno is set to ENOENT, indicating that the filename or path could not be found.
 
Parameters
path Path of existing file
buffer Pointer to structure that stores results
Remarks
The _stat function obtains information about the file or directory specified by path and stores it in the structure pointed to by buffer. _stat automatically handles multibyte-character string arguments as appropriate, recognizing multibyte-character sequences according to the multibyte code page currently in use.  
 
_wstat is a wide-character version of _stat; the path argument to _wstat is a wide-character string. _wstat and _stat behave identically except that _wstat does not handle multibyte-character strings.
 
The _stat structure, defined in SYS\STAT.H, includes the following fields.
 
st_gid Numeric identifier of group that owns file (UNIX-specific) This field will always be zero on NT systems. A redirected file is classified as an NT file.
 
st_atime Time of last access of file.
 
st_ctime Time of creation of file.
 
st_dev Drive number of the disk containing the file (same as st_rdev).
 
st_ino Number of the information node (the inode) for the file (UNIX-specific). On UNIX file systems, the inode describes the file date and time stamps, permissions, and content. When files are hard-linked to one another, they share the same inode. The inode, and therefore st_ino, has no meaning in the FAT, HPFS, or NTFS file systems.
 
st_mode Bit mask for file-mode information. The _S_IFDIR bit is set if path specifies a directory; the _S_IFREG bit is set if path specifies an ordinary file or a device. User read/write bits are set according to the file’s permission mode; user execute bits are set according to the filename extension.
 
st_mtime Time of last modification of file.
 
st_nlink Always 1 on non-NTFS file systems.
 
st_rdev Drive number of the disk containing the file (same as st_dev).
 
st_size Size of the file in bytes; a 64-bit integer for _stati64 and _wstati64
 
st_uid Numeric identifier of user who owns file (UNIX-specific). This field will always be zero on NT systems. A redirected file is classified as an NT file.
 
If path refers to a device, the size, time, _dev, and _rdev fields in the _stat structure are meaningless. Because STAT.H uses the _dev_t type that is defined in TYPES.H, you must include TYPES.H before STAT.H in your code
 
A+,

 

[edit]--Message édité par gilou--[/edit]


---------------
There's more than what can be linked! --    Iyashikei Anime Forever!    --  AngularJS c'est un framework d'engulé!  --
Reply

Marsh Posté le 06-06-2001 à 12:58:46    

plus d'info sur FindFirstFile

Code :
  1. The FindFirstFile function searches a directory for a file whose name matches the specified file name. FindFirstFile examines subdirectory names as well as file names.
  2. To specify additional attributes to be used in the search, use the FindFirstFileEx function.
  3. HANDLE FindFirstFile(
  4.   LPCTSTR lpFileName,               // file name
  5.   LPWIN32_FIND_DATA lpFindFileData  // data buffer
  6. );
  7. Parameters
  8. lpFileName
  9. [in] Pointer to a null-terminated string that specifies a valid directory or path and file name, which can contain wildcard characters (* and ?).
  10. Windows NT/2000: In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to nearly 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see File Name Conventions.
  11. Windows 95/98: This string must not exceed MAX_PATH characters.
  12. lpFindFileData
  13. [out] Pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory.
  14. Return Values
  15. If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose.
  16. If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
  17. Remarks
  18. The FindFirstFile function opens a search handle and returns information about the first file whose name matches the specified pattern. After the search handle has been established, use the FindNextFile function to search for other files that match the same pattern. When the search handle is no longer needed, close it by using the FindClose function.
  19. This function searches for files by name only; it cannot be used for attribute-based searches.
  20. You cannot use root directories as the lpFileName input string for FindFirstFile, with or without a trailing backslash. To examine files in a root directory, use something like "C:\*" and step through the directory with FindNextFile. To get the attributes of a root directory, use GetFileAttributes. Prepending the string "\\?\" does not allow access to the root directory.
  21. Similarly, on network shares, you can use an lpFileName of the form "\\server\service\*" but you cannot use an lpFileName that points to the share itself, such as "\\server\service".
  22. To examine any directory other than a root directory, use an appropriate path to that directory, with no trailing backslash. For example, an argument of "C:\windows" will return information about the directory "C:\windows", not about any directory or file in "C:\windows". An attempt to open a search with a trailing backslash will always fail.
  23. MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.
  24. The following code shows a minimal use of FindFirstFile.
  25. #define _WIN32_WINNT 0x0400
  26. #include "windows.h"
  27. int
  28. main(int argc, char *argv[])
  29. {
  30.   WIN32_FIND_DATA FindFileData;
  31.   HANDLE hFind;
  32.   printf ("Target file is %s.\n", argv[1]);
  33.   hFind = FindFirstFile(argv[1], &FindFileData);
  34.   if (hFind == INVALID_HANDLE_VALUE) {
  35.     printf ("Invalid File Handle. Get Last Error reports %d\n", GetLastError ());
  36.   } else {
  37.     printf ("The first file found is %s\n", FindFileData.cFileName);
  38.     FindClose(hFind);
  39.   }
  40.   return (0);
  41. }
  42. Requirements
  43.   Windows NT/2000: Requires Windows NT 3.1 or later.
  44.   Windows 95/98: Requires Windows 95 or later.
  45.   Header: Declared in Winbase.h; include Windows.h.
  46.   Library: Use Kernel32.lib.
  47.   Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.


 
http://msdn.microsoft.com/library/ [...] o_4qcl.htm

Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed