簡體   English   中英

在 Visual Studio 2010 和 Windows 中使用文件描述符

[英]Using File Descriptors in Visual Studio 2010 and Windows

我有一個 C++ 程序,它接受來自用戶的一些文本並將其保存到文本文件中。 以下是該程序的片段:

#include "stdafx.h"
#include <ctime>
#include <fcntl.h>
#include <iostream>
#include <string>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <Windows.h>

using namespace std;

int file_descriptor;
size_t nob;

int check_file(const char* full_path) //Method to check whether a file already exists
{
    file_descriptor = open(full_path, O_CREAT | O_RDWR, 0777); //Checking whether the file exists and saving its properties into a file descriptor
}

void write_to_file(const char* text) //Method to create a file and write the text to it
{
    time_t current = time(0); //Getting the current date and time
    char *datetime = ctime(&current); //Converting the date and time to string

    nob = write(file_descriptor, "----Session----\n\n"); //Writing text to the file through file descriptors
    nob = write(file_descriptor, "Date/Time: %s\n\n", datetime); //Writing text to the file through file descriptors
    nob = write(file_descriptor, "Text: %s", text); //Writing text to the file through file descriptors
    nob = write(file_descriptor, "\n\n\n\n"); //Writing text to the file through file descriptors
}

這個程序存在三個主要問題:

  1. Visual Studio 告訴我它無法打開源文件<unistd.h> (沒有這樣的文件或目錄)。

  2. 標識符open未定義。

  3. 標識符write未定義。

請問我該如何解決這些問題? 我在 Windows 7 平台上使用 Visual Studio 2010。 我想在我的程序中使用文件描述符。

Visual C++ 更喜歡為這些函數使用符合 ISO 的名稱: _open_write 然而 POSIX 名稱openwrite工作就好了。

您需要#include <io.h>才能訪問它們。

除此之外,您的代碼沒有正確使用write函數。 您似乎認為這是printf的另一個名稱,POSIX 不同意。


這段代碼在 Visual C++ 中編譯得很好。

#include <time.h>
#include <io.h>
#include <fcntl.h>

int file_descriptor;
size_t nob;

int check_file(const char* full_path) //Method to check whether a file already exists
{
    return open(full_path, O_CREAT | O_RDWR, 0777); // Checking whether the file exists and saving its properties into a file descriptor
}

void write_to_file(const char* text) // Function to write a binary time_t to a previously opened file
{
    time_t current = time(0); //Getting the current date and time

    nob = write(file_descriptor, &current, sizeof current);
}

如果您創建一個包含#include <io.h>unistd.h文件,並將其粘貼到您的系統包含路徑中,那么您將不需要任何代碼更改(假設您的代碼一開始就符合 POSIX 標准)。

openwrite是特定於 (Unix) 平台的。 文件訪問的 C 標准方法是FILE*fopenfwrite

如果你仍然想使用open / write你應該看看http://msdn.microsoft.com/en-us/library/z0kc8e3z(v=vs.100).aspx Microsoft 添加了對 open/write 的支持,但將(非 C 標准)函數重命名為_open / _write

如果您想在 Windows 下使用此代碼而無需更改,請嘗試 Cygwin: http : //www.cygwin.com/

但是,正如另一個答案中已經建議的那樣,使用 C 庫 FILE 函數重寫此代碼要好得多。 這將適用於任何操作系統。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM