Windows 8 파일 읽기 및 쓰기 작업

아무 말도 하지 않고 바로 코드를 찍어라.
#include <windows.h>
#include <ppltasks.h>
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Concurrency;

StorageFile^ openFile(String^ fileName)
{
    StorageFile^ file = nullptr;
    StorageFolder^ rootFolder = Windows::Storage::ApplicationData::Current->LocalFolder;

    task<StorageFile^>(rootFolder->GetFileAsync(fileName)).then([&](task<StorageFile^> getFileTask)
    {
        try
        {
            file = getFileTask.get();
        }
        catch (Platform::Exception^ e)
        {
        }
    }).wait();

    return file;
}

Array<byte>^ getFileContent(String^ fileName)
{
    Array<byte>^ data = nullptr;
    StorageFile^ file = openFile(fileName);
    if (file)
    {
        task<IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([&]

(task<IRandomAccessStream^> getStream)
        {  
            auto readStream = getStream.get();
            DataReader^ dataReader=ref new DataReader(readStream);
            int length = readStream->Size;
            if (length > 0)
            {
                data = ref new Array<byte>(length);
                task<unsigned int>(dataReader->LoadAsync(readStream->Size)).then([&](task<unsigned 

int> loadTask) {
                    loadTask.get();
                    dataReader->ReadBytes(data);
                }).wait();
            }
        }).wait();
    }

    return data;
}

bool setFileContent(String^ fileName, unsigned char* data, int size)
{
    size_t totalWritten = 0;
    bool complete = false;
    StorageFile^ file = openFile(fileName);
    if (file)
    {
        IRandomAccessStream^ readStream = nullptr;
        task<IRandomAccessStream^>(file->OpenAsync(FileAccessMode::ReadWrite)).then([&]

(task<IRandomAccessStream^> getStream)
        {  
            readStream = getStream.get();

            DataWriter^ dataWriter = ref new DataWriter(readStream);
            Array<unsigned char>^ arr = ref new Array<unsigned char>(data, size);

            dataWriter->WriteBytes(arr);
            task<unsigned int>(dataWriter->StoreAsync()).then([&](task<unsigned int> writeTask)
            {
                try
                {
                    totalWritten = writeTask.get();
                } catch (Platform::Exception^ ex) {}
            }).wait();

            task<bool>(dataWriter->FlushAsync()).then([&](task<bool> flushTask)
            {
                try
                {
                    complete = flushTask.get();
                } catch (Platform::Exception^ ex) {}
            }).wait();

            dataWriter->DetachStream();

        }).wait();
    }

    return complete;
}

좋은 웹페이지 즐겨찾기