2

我有一个 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。我想在我的程序中使用文件描述符。

4

3 回答 3

5

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);
}

如果您创建一个unistd.h包含 的文件#include <io.h>,并将其粘贴到您的系统包含路径中,那么您将不需要任何代码更改(假设您的代码一开始就与 POSIX 兼容)。

于 2012-11-02T16:09:55.403 回答
3

open并且write是(Unix)平台特定的。文件访问的 C 标准方法是FILE*,fopenfwrite.

如果你仍然想使用open/write你应该看看http://msdn.microsoft.com/en-us/library/z0kc8e3z(v=vs.100).aspx。Microsoft 添加了对 open/write 的支持,但将(非 C 标准)函数重命名为_open/ _write

于 2012-11-02T15:49:14.380 回答
-2

如果您想在 Windows 下使用此代码而不做任何更改,请尝试 Cygwin:http ://www.cygwin.com/

但是,正如另一个答案中已经建议的那样,使用 C 库 FILE 函数重写此代码要好得多。这适用于任何操作系统。

于 2012-11-02T15:54:42.080 回答