Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Файлы!!! Как узнать размер ... 
:(
    Опции темы
Doc_d0s
Дата 14.2.2005, 21:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 206
Регистрация: 15.12.2004
Где: в кресле

Репутация: 2
Всего: 3



Скажите плз оч надо !!!
Как узнать размер простого текстового файла??? smile smile
Посибо заранее!!!
--------------------
Админ- это вождь Apache'й :)
PM MAIL ICQ   Вверх
IEZ
Дата 14.2.2005, 21:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 295
Регистрация: 10.2.2005
Где: Санкт-Петербург

Репутация: нет
Всего: 3



А это не то?
Цитата
CFile::GetLength
Obtains the current logical length of the file in bytes.

virtual ULONGLONG GetLength( ) const;
Return Value
The length of the file.

Example
CFile* pFile = NULL;
   // Constructing a CFile object with this override may throw
   // a CFile exception, and won't throw any other exceptions.
   // Calling CString::Format() may throw a CMemoryException,
   // so we have a catch block for such exceptions, too. Any
   // other exception types this function throws will be
   // routed to the calling function.
   TRY
   {
      pFile = new CFile(_T("C:\\WINDOWS\\SYSTEM.INI"),
         CFile::modeRead | CFile::shareDenyNone);
      ULONGLONG dwLength = pFile->GetLength();
      CString str;
      str.Format(_T("Your SYSTEM.INI file is %I64u bytes long."), dwLength);
      AfxMessageBox(str);
   }
   CATCH(CFileException, pEx)
   {
      // Simply show an error message to the user.
      pEx->ReportError();
   }
   AND_CATCH(CMemoryException, pEx)
   {
      // We can't recover from this memory exception, so we'll
      // just terminate the app without any cleanup. Normally, an
      // an application should do everything it possibly can to
      // clean up properly and _not_ call AfxAbort().
      AfxAbort();
   }
   END_CATCH
   // If an exception occurs in the CFile constructor,
   // the language will free the memory allocated by new
   // and will not complete the assignment to pFile.
   // Thus, our clean-up code needs to test for NULL.
   if (pFile != NULL)   {
      pFile->Close();
      delete pFile;
   }
smile

Это сообщение отредактировал(а) IEZ - 15.2.2005, 00:20


--------------------
"Нужно делать так, как нужно, а как не нужно, делать не нужно" (с) Винни-Пух.
PM MAIL WWW ICQ   Вверх
IEZ
Дата 15.2.2005, 00:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 295
Регистрация: 10.2.2005
Где: Санкт-Петербург

Репутация: нет
Всего: 3



Можно и старенькой функцией:
Цитата
GetFileSize

The GetFileSize function retrieves the size of the specified file. The file size that can be reported by this function is limited to a DWORD value.

To retrieve a file size that is larger than a DWORD value, use the GetFileSizeEx function.


DWORD GetFileSize(
  HANDLE hFile,
  LPDWORD lpFileSizeHigh
);

Parameters
hFile
[in] Handle to the file whose size is to be returned. This handle must have been created with either the GENERIC_READ or GENERIC_WRITE access right. For more information, see File Security and Access Rights.
lpFileSizeHigh
[out] Pointer to the variable where the high-order word of the file size is returned. This parameter can be NULL if the application does not require the high-order word.
Return Values
If the function succeeds, the return value is the low-order doubleword of the file size, and, if lpFileSizeHigh is non-NULL, the function puts the high-order doubleword of the file size into the variable pointed to by that parameter.

If the function fails and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call GetLastError.

If the function fails and lpFileSizeHigh is non-NULL, the return value is INVALID_FILE_SIZE and GetLastError will return a value other than NO_ERROR.

Remarks
You cannot use the GetFileSize function with a handle of a nonseeking device such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.

The GetFileSize function retrieves the uncompressed size of a file. Use the GetCompressedFileSize function to obtain the compressed size of a file.

Note that if the return value is INVALID_FILE_SIZE, an application must call GetLastError to determine whether the function has succeeded or failed. The reason the function may appear to fail when it has not is that lpFileSizeHigh could be non-NULL or the file size could be 0xffffffff. In this case, GetLastError will return NO_ERROR upon success.

Или ее расширением:
Цитата
GetFileSizeEx

The GetFileSizeEx function retrieves the size of the specified file.


BOOL GetFileSizeEx(
  HANDLE hFile,
  PLARGE_INTEGER lpFileSize
);

Parameters
hFile
[in] Handle to the file whose size is to be returned. The handle must have been created with either the GENERIC_READ or GENERIC_WRITE access right. For more information, see File Security and Access Rights.
lpFileSize
[out] Pointer to a LARGE_INTEGER structure that receives the file size.
Return Values
If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.
smile




--------------------
"Нужно делать так, как нужно, а как не нужно, делать не нужно" (с) Винни-Пух.
PM MAIL WWW ICQ   Вверх
bel_nikita
Дата 15.2.2005, 00:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Эксперт
Сообщений: 2304
Регистрация: 12.10.2003
Где: Поезд №21/22 ( ст . Прага )

Репутация: 21
Всего: 47



А если не нужно WinAPI, то есть старый дедовский способ:
Код

long filesize(FILE *stream)
{
 long curpos, length;
 curpos = ftell(stream);
 fseek(stream, 0L, SEEK_END);
 length = ftell(stream);
 fseek(stream, curpos, SEEK_SET);
 return length;
}
...
FILE *fr;
long lSize = 0;
if((fr = fopen("Name.txt", "rb")) == NULL) {
 fprintf(stderr, "Cannot open file %s\n", sFName);
}
lSize = filesize(fr);
...



--------------------
user posted image — регистрация доменов от 150 руб.
PM MAIL WWW ICQ   Вверх
sergejzr
Дата 15.2.2005, 00:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Un salsero
Group Icon


Профиль
Группа: Админ
Сообщений: 13285
Регистрация: 10.2.2004
Где: Германия г .Ганновер

Репутация: 19
Всего: 360



Ну и я старый способ для всех платформ smile

Код

#include <sys/stat.h>
long fileLength(const char* filename)
{
   struct stat buf;

   if(stat(filename, &buf) != 0)
   {
       /* Произошла проблема при получении информации */
       return -1;
   }
   return (buf.st_size);
}



--------------------
PM WWW IM ICQ Skype GTalk Jabber AOL YIM MSN   Вверх
Doc_d0s
Дата 15.2.2005, 19:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 206
Регистрация: 15.12.2004
Где: в кресле

Репутация: 2
Всего: 3



Всем пасибо тема закрыта smile
--------------------
Админ- это вождь Apache'й :)
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++:Общие вопросы"
Earnest Daevaorn

Добро пожаловать!

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ :)
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе - для этого существует "Центр Помощи".
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0527 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.