问题描述
我正在尝试使用 Unix 系统调用复制 C stdio 库。首先,我尝试仅使用 fopen
UNIX 系统调用来模仿/重新创建 open
。
我有一个 File 类,我希望构造函数打开一个文件,该文件以我也传入的模式传递给构造函数。我想创建一个指向我打开的文件中第一个字节的指针open
,但不确定如何执行此操作。在文件类中,我有一个私有成员 char* curPtr
,我想用它来表示我在文件中所在位置的当前位置(在读取或写入时,我将在后面进一步使用)。
我不知道如何将 open
返回的文件描述符与 curPtr
数据成员“链接”。我目前在下面实现了一些代码,它基本上是将文件描述符(一个 int)类型转换为一个 char*(像这样:curPtr = (char*)fileDescriptor;
),但我不知道这是否正确。我想使用 curPtr*
逐字节索引我打开的文件,并能够在 curPtr*
指向的位置打印或写入单个字符。
文件类:
class File {
public:
class File_Exception: public std::exception {
};
static const int bufsiz = 8192;
static const int eof = -1;
File(const char *name,const char *mode = "r");
// Close the file. Make sure any buffered data is written to disk,// and free the buffer if there is one.
~File();
int fgetc();
int fputc(int c);
private:
const char* fileName; //stores the pointer to our file.
int fileMode; //stores our file mode.
char* filebuffer; //Buffer
char* curPtr; //I want to use this pointer to point to the current location we are in a file.
int fileDescriptor; //The file descriptor for this particular file object.
bool canWeRead = false; //flag to indicate if we have read access
bool canWeWrite = false; //flag to indicate if we have write access
int errorState = 0; //0 indicates we have no errors. 1 indicates error
};
File::File(const char *name,const char *mode) {
int fileMode = 0; //Initializing mode to 0
fileName = name; //Setting the file name of this File object to the name we pass in.
switch(*mode){
case 'r':
fileMode = O_RDONLY | O_CREAT;
canWeRead = true;
canWeWrite = false;
break;
case 'r+':
fileMode = O_RDWR | O_CREAT;
canWeRead = true;
canWeWrite = true;
break;
case 'w':
fileMode = O_WRONLY | O_CREAT;
canWeRead = false;
canWeWrite = true;
break;
case 'w+':
fileMode = O_RDWR | O_CREAT | O_Trunc;
canWeRead = true;
canWeWrite = true;
break;
default: //We should never reach the default case,so I assert(0)
assert(0);
}
fileDescriptor = open(name,fileMode);
assert(fileDescriptor >= 0); //If we dont get a positive nonnegative int,we have a problem.
//How do I set the value of curPtr to the first char in my File object?
curPtr = (char*)fileDescriptor; //I think that this works?
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)