WinPcap creating empty .pcap file - c++

Do you know how to create empty file pcap with winpcap dll? I buffer filtered packets in program memory and want to save when user click to export to .pcap file.
But when using pcap_open_offline(const char *fname, char *errbuf) can open file only if file exists. I tried fopen and other functions to create file previously (in binary mode too) but unsucessfully.
So how to get pcap_t handle pointer for pcap_dump_open(pcap_t *p, const char *fname) this way?
UPDATED:
I try to use this code
fileHandle = pcap_open_offline(pcap_file_path.c_str(), errbuf);
if (errbuf == nullptr) {
fprintf(stderr, "\nUnable to open the file %s.\n", pcap_file_path.c_str());
return 1;
}
if (fileHandle == nullptr) {
fprintf(stderr, "\nError to open file\n");//HERE IT FAILS
return 1;
}
dumpfile = pcap_dump_open(fileHandle, pcap_file_path.c_str());
if (dumpfile == NULL)
{
fprintf(stderr, "\nError opening output file\n");
return 1;
}
SOLUTION: (Creating a pcap file)
/*create fake handle*/
fileHandle = pcap_open_dead(DLT_EN10MB, 65535);
if (fileHandle == nullptr) {
fprintf(stderr, "\nError to open file\n");
return 1;
}
/* Open the dump file */
dumpfile = pcap_dump_open(fileHandle, file_path.c_str());
if (dumpfile == NULL)
{
fprintf(stderr, "\nError opening output file\n");
return 1;
}

Do you know how to create empty file pcap with winpcap dll? I buffer filtered packets in program memory and want to save when user click to export to .pcap file.
...
So how to get pcap_t handle pointer for pcap_dump_open(pcap_t *p, const char *fname) this way?
pcap_dump_open() returns a pcap_dumper_t * handle for use when writing the file; a pcap_t * is used for capturing or reading, not writing.
What you need to do, if you want to write a pcap file, is use pcap_dump_open(). If you have a pcap_t * from which you're reading or capturing the filtered packets, you should use that pcap_t * in the call to pcap_dump_open().

Related

C++: fopen() returns handle to empty file

I'm getting a strange file handle from fopen; the pointer itself isn't NULL, but the file it represents has no size, and feof(file) is already set... what could be causing this?
(I triple checked the file itself, it exists, has data, and the file's permissions are okay... and filename is set to "source/test_file.object.txt")
bool tagFile(const char * filename){
FILE * file = fopen(filename, "r");
if(file == NULL){ // file is not NULL
printf(" Couldn't open the file %s", filename);
return false;
}
int size = fseek(file, 0, SEEK_END); // size is 0
rewind(file);
while(feof(file)){
.... // never executes because feof(file) fails
}
}
0x002cc410 // value of 'file' in the debugger
_ptr=0x00000000 <Bad Ptr>
_cnt=0
_base=0x00000000 <Bad Ptr>
_flag = 1
_file = 3
The most common cause of this is simply opening a file which is empty. There are no bytes to read so EOF is immediate, but the file exists so fopen can't return NULL.

How to open a file with append mode only if it exist

The function fopen("file-name",a); will return a pointer to the end of the file. If the file exist it is opened, otherwise a new file is created.
Is it possible to use the append mode and open the file only if it already exist? (and return a NULL pointer otherwise).
Thanks in advance
To avoid race conditions, opening and checking for existence should be done in one system call. In POSIX this can be done with open as it will not create the file if the flag O_CREAT is not provided.
int fd;
FILE *fp = NULL;
fd = open ("file-name", O_APPEND);
if (fd >= 0) {
/* successfully opened the file, now get a FILE datastructure */
fp = fdopen (fd, "a")
}
open may fail for other reasons too. If you do not want to ignore all of them, you will have to check errno.
int fd;
FILE *fp = NULL;
do {
fd = open ("file-name", O_APPEND);
/* retry if open was interrupted by a signal */
} while (fd < 0 && errno == EINTR);
if (fd >= 0) {
/* successfully opened the file, now get a FILE datastructure */
fp = fdopen (fd, "a")
} else if (errno != ENOENT) { /* ignore if the file does not exist */
perror ("open file-name"); /* report any other error */
exit (EXIT_FAILURE)
}
First check if the file already exists. A simple code to do that might be like this:
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
It will return 0 if file doesn't exist...
and use it like this:
if(exists("somefile")){file=fopen("somefile","a");}

Creating text file into C++ addon of node.js

I want to know how i can create file and append data inside it in c++ addon (.cc) file of node.js ??
I have used below code to do same, but not able to find file "data.txt" in my ubuntu machine(reason behind it may be below code is not correct way to create file, but strange i haven't received any error/warning at compile time).
FILE * pFileTXT;
pFileTXT = fopen ("data.txt","a+");
const char * c = localReq->strResponse.c_str();
fprintf(pFileTXT,c);
fclose (pFileTXT);
Node.js relies on libuv, a C library to handle the I/O (asynchronous or not). This allows you to use the event loop.
You'd be interested in this free online book/introduction to libuv: http://nikhilm.github.com/uvbook/index.html
Specifically, there is a chapter dedicated to reading/writing files.
int main(int argc, char **argv) {
// Open the file in write-only and execute the "on_open" callback when it's ready
uv_fs_open(uv_default_loop(), &open_req, argv[1], O_WRONLY, 0, on_open);
// Run the event loop.
uv_run(uv_default_loop());
return 0;
}
// on_open callback called when the file is opened
void on_open(uv_fs_t *req) {
if (req->result != -1) {
// Specify the on_write callback "on_write" as last argument
uv_fs_write(uv_default_loop(), &write_req, 1, buffer, req->result, -1, on_write);
}
else {
fprintf(stderr, "error opening file: %d\n", req->errorno);
}
// Don't forget to cleanup
uv_fs_req_cleanup(req);
}
void on_write(uv_fs_t *req) {
uv_fs_req_cleanup(req);
if (req->result < 0) {
fprintf(stderr, "Write error: %s\n", uv_strerror(uv_last_error(uv_default_loop())));
}
else {
// Close the handle once you're done with it
uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
}
}
Spend some time reading the book if you want to write C++ for node.js. It's worth it.

Check unsupported file name for fopen

I'm trying to open a file to treat it later. My problem is that if my file name is not ANSI (Arabic, Hindi...) fopen_s and fopen refuse to open it and give me an Invalid argument error. I can't use CreateFile() to do that so I thought to check either my file name is supported by fopen or not(try to open it) and create a temporary file instead:
QString fileN=QString::fromWCharArray(fname);
QFileInfo file(DIRPath+"/"+fileN);
bool Supported=true;
if(file.exists()) {
QString temp;
char* Fname=(char*)malloc(260*sizeof(char));
strcpy(Fname,(QString(DIRPath+"/"+fileN).toStdString()).c_str());
FILE* Filedesc;
errno_t err=fopen_s(&Filedesc,Fname,"rb");
if(Filedesc!=NULL) {
qDebug()<<"\nfile opened ";
fclose(Filedesc);
} else if(err==22) {
qDebug()<<"\nfail to open file error 22: Invalid argument";
temp=QString(DIRPath+"/Temp"+QString::number(nb));
Supported=false;
} else qDebug()<<"\nfail to open file error"<<GetLastError()<<"errno"<<errno<<"strerrno"<<strerror(errno);
Fname=NULL;
free(Fname);
...
My question is: can anyone clarify for me the UNICODE/ANSI confusion? Am I safe so far or are there more precautions to consider? Is there a safer way to check if the given name is not ANSI?
Thank you in advance, any help will be appreciated.
EDIT 1
I tried this but in vain : CreateFile() return an INVALID_HANDLE_VALUE and GetLastError() return 0
//WCHAR fname[]=L"D:/أحدالأنشطة.txt";
char* name="D:/أحدالأنشطة.txt";
wchar_t* nameW=(wchar_t*)malloc(sizeof(wchar_t)*17);
qDebug()<<"s :"<<mbstowcs(nameW,name,17);
//QString path=QString::fromWCharArray(fname,17);
//QString path=QString::fromLatin1(name,17);
HANDLE fileHandle = CreateFile( nameW, // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);
if (fileHandle == INVALID_HANDLE_VALUE)
{
qDebug()<<"CreateFile failed!\n"<<GetLastError();
nameW=NULL;
free(nameW);
return 2;
}else
qDebug()<<"CreateFile succeeded!\n";
int fd = _open_osfhandle((intptr_t) fileHandle, _O_RDONLY);
FILE* fstr = _fdopen(fd, "r");
QFile indirect;
if (!indirect.open(fstr, QIODevice::ReadOnly))
qDebug()<<"QFile open against file descriptor failed!\n";
else
{
qDebug()<<"QFile open against file descriptor succeeded!\n";
indirect.close();
}
// This will fail
QFile direct(path);
if (!direct.open(QIODevice::ReadOnly))
qDebug()<<"QFile open of filename directly failed!\n";
else
{
qDebug()<<"QFile open of filename directly succeeded!\n";
direct.close();
}
nameW=NULL;
free(nameW);
EDIT 2
QString fname(QFile::decodeName("D:/أحدالأنشطة.txt"));
QFile qFile(fname);
bool b=qFile.open(QIODevice::ReadOnly);
if(b)
{
FILE* filedesc = fdopen(qFile.handle(), "rb");
if(filedesc!=NULL)
{
char* nb=(char*)malloc(2*sizeof(char));
qDebug()<<"opened ";
size_t size=fread(nb,sizeof(char),2,filedesc);
fclose(filedesc);
qDebug()<<"filedesc closed size "<<size<<"nb "<<QString::fromAscii(nb,2);
nb=NULL;
free(nb);
}else qDebug()<<"filedesc failed error"<<strerror(errno);
}else
qDebug()<<"qFile failed error"<<strerror(errno);
You should probably use QFile to open the file, and then pass QFile::handle() to your C function. In the C code you would then use fdopen() to associate a FILE* stream to the file descriptor. Note that the mode you use in fdopen() should be compatible with the mode you used in QFile::open(). For example:
void c_func(int fd)
{
FILE* file = fdopen(fd, "rb");
// ...
}

Ofstream not writing to file C++

I have this method which supposed to get a buffer and write some content to a file:
void writeTasksToDevice()
{
TaskInfo *task;
unsigned int i = lastTaskWritten;
printf("writing elihsa\n");
outputFile.write(" Elisha2", 7);
//pthread_mutex_lock(&fileMutex);
for(; i < (*writingTasks).size(); i++)
{
task = (*writingTasks).at(i);
if(NULL == task)
{
printf("ERROR!!! in writeTasksToDevice - there's a null task in taskQueue. By "
" design that should NEVER happen\n");
exit(-1);
}
if(true == task->wasItWritten)
{
//continue;
}
else // we've found a task to write!
{
printf("trying to write buffer to file\n");
printf("buffer = %s, length = %d\n", task->buffer, task->length);<====PRINT HERE IS OK< PRINTING WHAT IS WANTED
outputFile.write(task->buffer, task->length); <===SHOULD WRITE HERE
printf("done writing file\n");
}
}
//pthread_mutex_unlock(&fileMutex);
// TODO: check if we should go to sleep and wait for new tasks
// and then go to sleep
}
the buffer content is:
task->buffer: elishaefla
task->length: 10
i opened the stream in another init function using:
outputFile.open(fileName, ios :: app);
if(NULL == outputFile)
{
//print error;
return -1;
}
but at the end, the file content is empty, nothing is being written.
any idea why?
You did not provide enough information to answer the question with certainty, but here are some of the issues you might be facing:
You did not flush the buffer of the ofstream
You did not close the file that you are trying to open later on (if I'm correct, outputFile is a global variable, so it is not closed automatically until the end of the program)