Mat*_*hew 2 c++ file file-descriptor
我有一个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(¤t); //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
}
Run Code Online (Sandbox Code Playgroud)
该计划有三个主要问题:
Visual Studio告诉我它无法打开源文件<unistd.h>(没有这样的文件或目录).
标识符open未定义.
标识符write未定义.
我该如何解决这些问题呢?我在Windows 7平台上使用Visual Studio 2010.我想在我的程序中使用文件描述符.
Visual C++更喜欢这些函数的符合ISO的名称:_open和_write.但POSIX命名open并且write工作得很好.
您需要#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, ¤t, sizeof current);
}
Run Code Online (Sandbox Code Playgroud)
如果您创建一个unistd.h包含#include <io.h>并将其粘贴到系统包含路径中的文件,那么您将不需要任何代码更改(假设您的代码与POSIX兼容).
| 归档时间: |
|
| 查看次数: |
8478 次 |
| 最近记录: |