Permission Denied when I use remove() - c++

I have this issue. I have a C++ program; the program successfully make files in which I save records. In one procedure I edit one record and make another file with different name. At the end I close the both files and when I try to delete old one and rename the new one I have this error:
Error deleting file: Permission denied.
void SoldDevices()
{
int soldQuantity = 0;
char soldModel[20];
ElShop tempVar;
FILE *newFile;
printf("Enter model of sold device: ");
gets(soldModel);
file = fopen(fileName, "r+");
fread(&shop, sizeof(shop), 1, file);
while (!feof(file))
{
if (strcmp(shop.model, soldModel) == 0)
{
tempVar = shop;
break;
}
fread(&shop, sizeof(shop), 1, file);
}
fclose(file);
printf("Enter how much devices are sold: ");
scanf("%d", &soldQuantity);
while (tempVar.quantity < soldQuantity)
{
printf("No items available!\n");
printf("Enter how much devices are sold: ");
scanf("%d", &soldQuantity);
}
tempVar.quantity = tempVar.quantity - soldQuantity;
printf("%d\n", tempVar.quantity);
file = fopen(fileName, "rb");
newFile = fopen("New", "wb");
fread(&shop, sizeof(shop), 1, file);
while (!feof(file))
{
if(strcmp(soldModel, shop.model) == 0)
{
fwrite(&tempVar, sizeof(shop), 1, newFile);
}
else
{
fwrite(&shop, sizeof(shop), 1, newFile);
}
fread(&shop, sizeof(shop), 1, file);
}
fclose(newFile);
fclose(file);
if( remove( fileName ) != 0 )
perror( "Error deleting file" );
else
puts( "File successfully deleted" );
rename("New", fileName);
}
Did anyone have some ideas to resolve the problem?

I once had the same problem like you, but now I had solved it.
You must had some file-pointers that haven't closed when you used remove(). It does not have to be in the same .cpp file, maybe in different files.
Take me as an example, I think I had closed the file, but later I found out that I have "return" sentences before fclose() which results in the file not being closed correctly.
PS:
1. I have 3 .cpp files.
The file containing remove() was used after the file(A.cpp) that didn't make the file closed correctly.
Because the A.cpp don't closed the file correctly so that the Permission Denied appears.
My English is poor. Hope this can help you.

Related

Cannot open file /sys/class/net/eth0/carrier

I have following function isEthernetCableConnected() which I am calling in a thread in continuous loop. After a long time I started to get log "Could not open /sys/class/net/eth0/carrier". How can it be possible? If it is possible then please give me some idea how to open the file every time.
ETH_FILE_CARRIER /sys/class/net/eth0/carrier
int isEthernetCableConnected(){
FILE *fp = fopen(ETH_FILE_CARRIER, "r");
int result;
if(fp == NULL) {
CLog::getInstance()->error("utility",__LINE__,__FILE__,"networked::isEthernetConnected, Could not open %s", ETH_FILE_CARRIER);
return 0;
}
fscanf(fp,"%d",&result);
fclose(fp);
return result;
}
Please refer the below link, it might help you
http://wikistack.com/how-to-check-if-ethernet-cable-is-connected-linux
In this link, they are trying to open the file in different way. May be you can try that.

Symbolic links in libzip

I'm using libzip in a c++ application for Linux that will need to be able to zip/unzip directories containing symbolic links. I want to add the link itself without following it. Reading out the link with readlink() and adding it to the zip archive results in a nonsense standard file when unzipped with unzip.
Solution does not need to be portable, it will only be used under Linux. The linux zip command has a --symlinks flags so the zip standard should support it. System calls are not really an option, the number of files is quite large and this makes the application extremely slow.
Is it possible to add symlinks with libzip, and how?
Thanks,
Sander
Based on documentation: no
According to its webpage, libzip is based on zlib. The zip program used in Linux, etc, is info-zip, which does not use zlib, but is self-contained (and contains features not in zlib).
Yes it's possible.
Below a function i use for zipping a list of files in c-code.
The files to zip are stored in a cJSON struct,no uid/gid set and files/directories relative to a directory "base" (as that is my appliction).
The Function returns 0 on success.
int list_zip_it(char * upload_zip_name,char * base, cJSON * filelist)
{
int result=0;
int error_n = 0;
struct zip *archive = zip_open(upload_zip_name, ZIP_TRUNCATE | ZIP_CREATE, &error_n);
if(!archive)
{
printf(stderr,"could not open or create archive\n");
return -1;
}
mode_t mode=0;
cJSON * item;
cJSON_ArrayForEach(item,filelist)
{
char * path=NULL;
path=item->valuestring;
// stat the item
struct stat sb;
if (stat(path, &sb) == 0 ) mode=sb.st_mode;
zip_uint32_t attr=0;
attr=((mode ) << 16L);
char rel_file[1024];
if (strncmp(path,CI_PROJECT_DIR,strlen(base))==0 )
{
snprintf(rel_file,1024,"%s",path+strlen(base)+1);
printf("archive filename: %s\n",rel_file);
}
else
{
fprintf(stderr,"filename outside base-derectory\n");
continue;
}
if (S_ISDIR(mode))
{
int index = (int)zip_add_dir(archive, rel_file);
if (index>0) zip_file_set_external_attributes(archive, index, 0, ZIP_OPSYS_UNIX, attr);
}
else if (S_ISLNK(mode)) // symlink
{
char link[1024];//=calloc(1, 1024);
memset(link, 0, 1024);
ssize_t size_link=readlink(path , link, 1023);
if (size_link > 0)
{
struct zip_source *source = zip_source_buffer(archive , link, ( zip_uint64_t)size_link,0);
if (source)
{
int index = (int)zip_add(archive, rel_file, source);
if (index>0) zip_file_set_external_attributes(archive, index, 0, ZIP_OPSYS_UNIX, attr);
}
else
{
printf(stderr,"failed to create source buffer: %s \n", zip_strerror(archive) );
zip_source_free(source);
}
}
else error("failed to read link: %s \n",path );
}
else if (S_ISREG(mode))
{
struct zip_source *source = zip_source_file(archive, path, 0, 0);
if(source == NULL)
{
error("failed to create source buffer: %s \n", zip_strerror(archive) );
result=1;
break;
}
// todo calculate filename relative to project_dir
int index = (int)zip_add(archive, rel_file, source);
if(index < 0 )
{
int zep,sep;
zip_error_get(archive, &zep, &sep);
if (zep== ZIP_ER_EXISTS )
{
fprintf(stderr,"failed to add file to archive: %s \n", zip_strerror(archive) );
zip_source_free(source);
}
else
{
fprintf(stderr,"failed to add file to archive: %s \n", zip_strerror(archive) );
zip_source_free(source);
result=1;
break;
}
}
else
{
zip_file_set_external_attributes(archive, index, 0, ZIP_OPSYS_UNIX, attr);
}
}
}
zip_close(archive);
return result;
}

Implement "File open in folder" feature for my C++ application in linux

I'm trying to implement the "Open In Folder" functionality that you seen in firefox and download managers. This is the code that I've come up so far, and I decided to use nautilux program to open the file.
int File::openTempFile(std::string temp_file_dir)
{
std::string file_path = temp_file_dir + "/" ;
file_path = file_path + this->additional_info ;
// if there is already an temporary file then delete it//
if( temporary_file != "" )
{
// :TODO: open temporary file stack //
// so when the application dinit we could remove those //
// remove(temporary_file.c_str() );
}
/* write temporary file */
FILE* fp = fopen (file_path.c_str(), "w");
if( fp== NULL)
return FALSE;
fwrite( m_data, 1, m_size, fp);
fclose(fp);
// now open it using natulus //
char * parmList[] = {strdup("nautilus"),strdup(file_path.c_str() )} ;
int pid;
if(( pid= fork() ) == -1)
perror("fork failed");
if( pid ==0 ){
int a = execvp("nautilus" , parmList);
printf("exevp failed to load the temporary file");
}
temporary_file = file_path ;
return TRUE;
}
but the error is natulux open three windows and can't figure out where is my bug.
Any idea ?

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)

Inconsistent behaviour with fopen in C/C++

I'm working with a library which opens the same file many times. It checks the header of the file to make sure that it is the correct format. The first 1212 times it opens the file, it behaves correctly. The 1213th time, the bytes read out from the file are different. Can anyone suggest why this might be happening?
Unfortunately I can't make a small reproducible example - and it takes 20 minutes to run through to this point. So I'm wondering if there are any subtleties of fopen which I might have missed, or something else which might have a bearing on this execution.
The code is below. Many instances of the class are created, and each on has initialise() called with the same filename. The first 1212 times, the output is:
Expecting: '?'
?lon-1800????%#LYB1800????%#LYB100????%#LYB
lat-900??p-2?%#HYB900??p-2?%#HYB10??p-2?%#HYB
? soilcode0 ?? ?-2?&#AYB12 ?? ?-2?&#AYB1 ?? ?-2?&#AYBmtemp-600??x.2?&#6YB600??x.2?&#6YB10??x.2?&#6YB
?mprec0???H2?&#.YB99999???H2?&#.YB1999???H2?&#.YB?msun0???A2?&#%YB1000???A2?&#%YB100???A2?&#%YB
?
Got: '?'
?lon-1800????%#LYB1800????%#LYB100????%#LYB
lat-900??p-2?%#HYB900??p-2?%#HYB10??p-2?%#HYB
? soilcode0 ?? ?-2?&#AYB12 ?? ?-2?&#AYB1 ?? ?-2?&#AYBmtemp-600??x.2?&#6YB600??x.2?&#6YB10??x.2?&#6YB
?mprec0???H2?&#.YB99999???H2?&#.YB1999???H2?&#.YB?msun0???A2?&#%YB1000???A2?&#%YB100???A2?&#%YB
?
The last time I get:
Expecting: '?'
?lon-1800????%#LYB1800????%#LYB100????%#LYB
lat-900??p-2?%#HYB900??p-2?%#HYB10??p-2?%#HYB
? soilcode0 ?? ?-2?&#AYB12 ?? ?-2?&#AYB1 ?? ?-2?&#AYBmtemp-600??x.2?&#6YB600??x.2?&#6YB10??x.2?&#6YB
?mprec0???H2?&#.YB99999???H2?&#.YB1999???H2?&#.YB?msun0???A2?&#%YB1000???A2?&#%YB100???A2?&#%YB
?
Got: ' lon lat year
The function is as follows:
class Archive {
private:
FILE* pfile;
<snip>
bool initialise(char* filename) {
int i;
unsigned char* pheader;
if (pfile) fclose(pfile);
pfile=fopen(filename,"rb");
if (!pfile || pfile == NULL ) {
printf("Could not open %s for input\n",filename);
return false;
}
pheader=new unsigned char[CRU_1901_2002_HEADERSIZE-4];
if (!pheader) {
printf("Out of memory\n");
fclose(pfile);
pfile=NULL;
return false;
}
::rewind(pfile);
fread(pheader,CRU_1901_2002_HEADERSIZE-4,1,pfile);
printf( "Expecting: '%s'\n", CRU_1901_2002_HEADER);
for( int j = 0; j < CRU_1901_2002_HEADERSIZE-4;j++ )
printf( "%c", CRU_1901_2002_HEADER[j]);
printf( "\nGot: '%s'\n", pheader);
for( int j = 0; j < CRU_1901_2002_HEADERSIZE-4;j++ )
printf( "%c", pheader[j]);
printf( "\n");
for (i=0;i<CRU_1901_2002_HEADERSIZE-4;i++) {
if (pheader[i]!=CRU_1901_2002_HEADER[i]) {
fclose(pfile);
pfile=NULL;
delete pheader;
return false;
}
}
delete pheader;
::rewind(pfile);
fseek(pfile,CRU_1901_2002_HEADERSIZE+CRU_1901_2002_DATA_LENGTH*CRU_1901_2002_NRECORD,SEEK_CUR);
recno=0;
iseof=false;
return true;
}
public:
Archive() {
pfile=NULL;
}
Archive() {
if (pfile) fclose(pfile);
}
Are you sure that there is data in the 1213th position? or, are these data are correct?
I suggest you mount a file with more than 1213th records and do a test to confirm if there is a read error or not in this position.
It turns out this is down to too many files being open. Changing the program elsewhere to open less files fixes it.
Checking fread returns 1, except for the last one, where it returns 0.
However, I don't understand why fopen gives back a non-null file pointer when it can't open the file. In test code, it returns NULL, which is then caught as expected.