Ошибка если файл пустой с

How do I check if a file is empty in C#?

I need something like:

if (file is empty)
{
    // do stuff
}

else
{
    // do other stuff
}

Lauren Rutledge's user avatar

asked Jun 9, 2010 at 16:15

Arcadian's user avatar

1

Use FileInfo.Length:

if( new FileInfo( "file" ).Length == 0 )
{
  // empty
}

Check the Exists property to find out, if the file exists at all.

answered Jun 9, 2010 at 16:16

tanascius's user avatar

tanasciustanascius

52.9k22 gold badges113 silver badges136 bronze badges

3

FileInfo.Length would not work in all cases, especially for text files. If you have a text file that used to have some content and now is cleared, the length may still not be 0 as the byte order mark may still retain.

You can reproduce the problem by creating a text file, adding some Unicode text to it, saving it, and then clearing the text and saving the file again.

Now FileInfo.Length will show a size that is not zero.

A solution for this is to check for Length < 6, based on the max size possible for byte order mark. If your file can contain single byte or a few bytes, then do the read on the file if Length < 6 and check for read size == 0.

public static bool IsTextFileEmpty(string fileName)
{
    var info = new FileInfo(fileName);
    if (info.Length == 0)
        return true;

    // only if your use case can involve files with 1 or a few bytes of content.
    if (info.Length < 6)
    {
        var content = File.ReadAllText(fileName);   
        return content.Length == 0;
    }
    return false;
}

answered Sep 26, 2019 at 19:04

TDao's user avatar

TDaoTDao

5044 silver badges13 bronze badges

1

The problem here is that the file system is volatile. Consider:

if (new FileInfo(name).Length > 0)
{  //another process or the user changes or even deletes the file right here

    // More code that assumes and existing, empty file
}
else
{


}

This can and does happen. Generally, the way you need to handle file-io scenarios is to re-think the process to use exceptions blocks, and then put your development time into writing good exception handlers.

answered Jun 9, 2010 at 16:29

Joel Coehoorn's user avatar

Joel CoehoornJoel Coehoorn

397k113 gold badges567 silver badges792 bronze badges

1

if (!File.Exists(FILE_NAME))
{
    Console.WriteLine("{0} does not exist.", FILE_NAME);
    return;
}

if (new FileInfo(FILE_NAME).Length == 0)  
{  
    Console.WriteLine("{0} is empty", FILE_NAME);
    return;
} 

Lauren Rutledge's user avatar

answered Jun 9, 2010 at 16:26

Mike's user avatar

MikeMike

5,8888 gold badges57 silver badges94 bronze badges

1

I’ve found that checking the FileInfo.Length field doesn’t always work for certain files. For instance, and empty .pkgdef file has a length of 3. Therefore, I had to actually read all the contents of the file and return whether that was equal to empty string.

answered Jun 25, 2015 at 19:40

coole106's user avatar

coole106coole106

611 silver badge1 bronze badge

1

This is how I solved the problem. It will check if the file exists first then check the length. I’d consider a non-existent file to be effectively empty.

var info = new FileInfo(filename);
if ((!info.Exists) || info.Length == 0)
{
    // file is empty or non-existant    
}

answered Dec 23, 2014 at 21:32

Walter Stabosz's user avatar

Walter StaboszWalter Stabosz

7,4275 gold badges43 silver badges75 bronze badges

In addition to answer of @tanascius, you can use

try
{
    if (new FileInfo("your.file").Length == 0)
    {
        //Write into file, i guess    
    }
} 
catch (FileNotFoundException e) 
{
    //Do anything with exception
}

And it will do it only if file exists, in catch statement you could create file, and run code agin.

miguelmpn's user avatar

miguelmpn

1,8191 gold badge19 silver badges25 bronze badges

answered Jan 2, 2015 at 22:21

ArsenArsen's user avatar

ArsenArsenArsenArsen

3126 silver badges16 bronze badges

1

What if file contains space? FileInfo("file").Length is equal to 2.
But I think that file is also empty (does not have any content except spaces (or line breaks)).

I used something like this, but does anybody have better idea?
May help to someone.

string file = "file.csv";
var fi = new FileInfo(file);
if (fi.Length == 0 || 
    (fi.Length < 100000 
     && !File.ReadAllLines(file)
        .Where(l => !String.IsNullOrEmpty(l.Trim())).Any()))
{
    //empty file
}

answered Sep 7, 2015 at 13:53

Marek Barilla's user avatar

3

You can use this function if your file exists and is always copied to your debug/release directory.

/// <summary>
/// Include a '/' before your filename, and ensure you include the file extension, ex. "/myFile.txt"
/// </summary>
/// <param name="filename"></param>
/// <returns>True if it is empty, false if it is not empty</returns>
private Boolean CheckIfFileIsEmpty(string filename)
{
    var fileToTest = new FileInfo(Environment.CurrentDirectory + filename);
    return fileToTest.Length == 0;
}

Lauren Rutledge's user avatar

answered Mar 8, 2013 at 15:12

Kyle's user avatar

Perhaps something akin to:

bool is_empty(std::ifstream& pFile)
{
    return pFile.peek() == std::ifstream::traits_type::eof();
}

Short and sweet.


With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.

Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof(). Ergo, we just peek() at the stream and see if it’s eof(), since an empty file has nothing to peek at.

Note, this also returns true if the file never opened in the first place, which should work in your case. If you don’t want that:

std::ifstream file("filename");

if (!file)
{
    // file is not open
}

if (is_empty(file))
{
    // file is empty
}

// file is open and not empty

0 / 0 / 0

Регистрация: 04.11.2015

Сообщений: 9

1

Проверка на пустоту файла С++

14.03.2016, 12:32. Показов 41283. Ответов 2


Студворк — интернет-сервис помощи студентам

Помогите реализовать проверку на наличие файла и его пустоту. Если файл не открывается, вывести ошибку, если открывается, то проверить есть ли в нем данные.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

14.03.2016, 12:32

2

yrceus

88 / 88 / 80

Регистрация: 25.08.2013

Сообщений: 337

14.03.2016, 12:44

2

Лучший ответ Сообщение было отмечено KaTRiNA13 как решение

Решение

C++
1
2
3
    fstream file("file.txt");
    if (!file.is_open()) cout << "Not openn"; // если не открылся
    else if (file.peek() == EOF) cout << "Fail emptyn"; // если первый символ конец файла

.peek() смотрит, но не извлекает.



3



nikniknik2016

15 / 15 / 8

Регистрация: 02.03.2016

Сообщений: 37

14.03.2016, 12:45

3

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <stdio.h>
 
using namespace std;
 
int main()
{
    const char filename[] = "1.txt";
 
    FILE* f = fopen(filename, "rb");
    if(!f)
    {
        cout << "File is not exists" << endl;
        return 0;
    }
 
    char a;
    size_t readed = fread(&a, 1, 1, f);
 
    if(readed)
        cout << "File contains data" << endl;
    else
        cout << "File NOT contains data" << endl;
 
    return 0;
}



0



Возможно, что-то похожее на:

bool is_empty(std::ifstream& pFile)
{
    return pFile.peek() == std::ifstream::traits_type::eof();
}

Короткий и сладкий.


С учетом вашей ошибки другие ответы используют доступ к файлам в стиле C, где вы получаете FILE* с определенными функциями.

Напротив, мы с вами работаем с потоками С++ и поэтому не можем использовать эти функции. Вышеприведенный код работает простым способом: peek() заглянет в поток и вернет, не удаляя, следующий символ. Если он достигнет конца файла, он возвращает eof(). Ergo, мы просто peek() в потоке и видим, если он eof(), так как пустому файлу нечего заглядывать.

Примечание. Это также возвращает true, если файл никогда не открывается в первую очередь, что должно работать в вашем случае. Если вы этого не хотите:

std::ifstream file("filename");

if (!file)
{
    // file is not open
}

if (is_empty(file))
{
    // file is empty
}

// file is open and not empty
Определено в заголовке <filesystem>
bool is_empty( const std::filesystem::path& p );
bool is_empty( const std::filesystem::path& p, std::error_code& ec );
(since C++17)

Проверяет,относится ли данный путь к пустому файлу или каталогу.

Parameters

p путь изучения
ec код ошибки для модификации в случае ошибки

Return value

true если файл, указанный с помощью p , или тип, указанный как s , относится к пустому файлу или каталогу, в противном случае — значение false . Не перебрасывающая перегрузка возвращает false , если происходит ошибка.

Exceptions

Перегрузка, которая не принимает std::error_code& параметр , создает filesystem::filesystem_error для базовых ошибок API ОС, созданных с p в качестве первого аргумента пути и кодом ошибки ОС в качестве аргумента кода ошибки. Перегрузка, принимающая std::error_code& параметр, задает для него код ошибки API ОС, если вызов API ОС завершается сбоем, и выполняет ec.clear() , если ошибок не возникает. Любая перегрузка, не помеченная как noexcept , может вызвать std::bad_alloc , если выделение памяти не удалось.

Example

#include <filesystem>
#include <fstream>
#include <iostream>
#include <cstdio>
 
int main()
{
    namespace fs = std::filesystem;
 
    const fs::path tmp_dir{ fs::temp_directory_path() };
    std::cout << std::boolalpha
              << "Temp dir: " << tmp_dir << 'n'
              << "is_empty(): " << fs::is_empty(tmp_dir) << 'n';
 
    const fs::path tmp_name{ tmp_dir / std::tmpnam(nullptr) };
    std::cout << "Temp file: " << tmp_name << 'n';
 
    std::ofstream file{ tmp_name.string() };
    std::cout << "is_empty(): " << fs::is_empty(tmp_name) << 'n';
    file << "cppreference.com";
    file.flush();
    std::cout << "is_empty(): " << fs::is_empty(tmp_name) << 'n'
              << "file_size(): " << fs::file_size(tmp_name) << 'n';
    file.close();
    fs::remove(tmp_name);
}

Possible output:

Temp dir: "/tmp"
is_empty(): false
Temp file: "/tmp/fileCqd9DM"
is_empty(): true
is_empty(): false
file_size(): 16

Defect reports

Следующие отчеты о дефектах,изменяющих поведение,были применены ретроактивно к ранее опубликованным стандартам C++.

DR Applied to Поведение в опубликованном виде Correct behavior
LWG 3013 C++17 error_code Перегрузка error_code помечена как noexcept, но может выделить память noexcept removed

See also

(C++17)(C++17)

определяет атрибуты файла
определяет атрибуты файла,проверяя цель симлинков.
(function)

(C++17)

проверяет,относится ли путь к существующему объекту файловой системы
(function)


C++

  • std::filesystem::is_character_file

    Проверяет,соответствует ли статус или путь заданного файла специальному символу,определяемому POSIX S_ISCHR.

  • std::filesystem::is_directory

    Проверяет,соответствует ли заданный статус файла или путь каталогу.

  • std::filesystem::is_fifo

    Проверяет,соответствует ли статус или путь заданного файла FIFO pipe,как определено POSIX S_ISFIFO.

  • std::filesystem::is_other

    Проверяет,соответствует ли заданный статус файла или путь типу other true,если файл,на который ссылается p или тип s,не является обычным каталогом,

Понравилась статья? Поделить с друзьями:
  • Ошибка если после запятой нет пробела
  • Ошибка если поле не заполнено 1с
  • Ошибка если память не может быть рид
  • Ошибка если не является приложением win 32
  • Ошибка если не работает насос