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
}

このプログラムには 3 つの主な問題があります。

  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です。

それでも使用したい場合は、openhttp://msdn.microsoft.com/en-us/library/z0kc8e3z(v=vs.100).aspxをご覧ください。Microsoft は open/write のサポートを追加しましたが、(非 C 標準) 関数の名前を/に変更しました。write_open_write

于 2012-11-02T15:49:14.380 に答える
-2

このコードを変更せずに Windows で使用する場合は、Cygwin を試してください: http://www.cygwin.com/

ただし、別の回答で既に提案されているように、C ライブラリの FILE 関数を使用してこのコードを書き直す方がはるかに優れています。これはどのOSでも動作します。

于 2012-11-02T15:54:42.080 に答える