方法一:_sopen()
:具體函數描述sopen()
int _sopen(const char *filename, int oflag, int shflag [, int pmode ]);
參數:filename 文件名 oflag 允許的操作類型 shflag 允許的共享類型 pmode 權限設置。
返回值 : 其中每個函數都將爲打開的文件返回文件描述符。
如果 filename 或 oflag 是 NULL 指針,或者如果 oflag 或 shflag 不在有效值範圍內,則調用的參數處理程序無效,如參數驗證中所述。 如果允許執行繼續,則這些函數將返回 -1 並將 errno 設置爲以下值之一。
EACCES 給定路徑是目錄,或者文件是隻讀的,但是已嘗試打開以供寫入操作。
EEXIST 已指定 _O_CREAT 和 _O_EXCL 標誌,但 filename 已經存在。
EINVAL 無效的 oflag 或 shflag 參數。
EMFILE 沒有更多可用的文件描述符。
ENOENT 未找到文件或路徑。
備註: 寬字符版 int _wsopen( const wchar_t *filename, int oflag, int shflag [, int pmode ] );
代碼
#include <sstream>
#include <fstream>
#include <fcntl.h>
#include <share.h>
string strPath = AnsiString(strResaveName.c_str()).c_str();
while(1)
{
//BCB XE2 不識別_SH_DENYNO只能用0x40表示
fd = _sopen( strPath.c_str(), _O_RDWR/*打開文件以供讀取和寫入*/, 0x40/*允許讀取和寫入訪問*/, _S_IREAD | _S_IWRITE/*允許讀取和寫入*/ );
if(-1 == fd)
{
if(IDOK == MessageBox(NULL,"測試結果.xls已被打開,請先關閉文件","提示", MB_OKCANCEL))
{
continue;
}
else
{
return;
}
}
else
{
_close(fd); //需要關閉,否則文件被打開產生臨時文件
break;
}
}
如果Excel文件被打開,fd的值爲-1;否則則返回3(測試實際運行結果);
方法二:文件流讀寫
代碼:
ofstream是從內存到硬盤,ifstream是從硬盤到內存,其實所謂的流緩衝就是內存空間;
#include <iostream>
#include <fstream>
using namespace std;
#define F_PATH "d:\\example.xlsx"
int main(void)
{
ofstream iofile(F_PATH,ios::in|ios::out|ios::binary);//打開文件, 默認調用了open()函數
if(!iofile)//如果打開失敗
{
cerr<<"open error!"<<endl;//顯示出錯信息
abort();//程序退出
}
return 0;
}
如果Excel文件被打開,提示“open error”(測試實際運行結果);