Why remove and rename functions does not work in my program? - c

When I try to delete a file using the fowling lines of code, I get as result that the both files (stock.dat and clone.dat) exists after the end of the program (as result i want to exist only the renamed stock.dat (=original name was clone.dat)). Thanks in advance.
int code;
FILE *stock=fopen("stock.dat","rb");
FILE *stc_clone=fopen("clone.dat","wb");
printf("PLEASE TYPE THE CODE OF THE PRODUCT YOU WISH TO DELETE:\t");
scanf(" %d",& code);
printf("\n");
fseek(stock,0,SEEK_END);
int fl_size=ftell(stock);
int quantity= fl_size/sizeof(product);
rewind(stock);
prdct prd_pntr= (product *) malloc(sizeof(product)*quantity);
assert(prd_pntr);
fread(prd_pntr,sizeof(product),quantity,stock);
int i;
for(i=0;i<quantity;i++){
if(prd_pntr[i].code==code){
continue;
}else{
fprintf(stc_clone,"%d %s %d",prd_pntr[i].code,prd_pntr[i].description,prd_pntr[i].volume);
}
}
fclose(stc_clone);
fclose(stock);
remove(stock);
rename("clone.dat","stock.dat");
free(prd_pntr);
printf("\n\a THE PRODUCT DELETED!!!\n");

Your function does not remove the file because you are passing FILE* instead of char* to the remove function:
FILE *stock = fopen("stock.dat","rb");
...
fclose(stock);
remove(stock); // <<== HERE: you are supposed to pass a name, not FILE*
To fix the problem, change the remove line as followsL
remove("stock.dat");

Related

C Transforming array into string using sprintf

I have scanned "ABCDEFGHIJK" with fscanf into a char array[26]. Then I got "ABCDEFGHIJK" using "for" into another array[11]. Now I need to get to an "ABCDEFGHIJK.mp4" array[15] in order to feed that filename into a rename function.
I don't know much about C programming besides printf, scanf, for and while.
sprintf(filename, "%c%c%c%c%c%c%c%c%c%c%c.mp4", codigo[0], codigo[1], codigo[2], codigo[3], codigo[4], codigo[5], codigo[6], codigo[7], codigo[8], codigo[9], codigo[10]);
This code above seems to work, but I wonder if there is a simpler way (especially for bigger arrays)?
Clarification: I have a txt file, formatted with these containing the filenames without extension and the human filename. I'm trying to make a program that will rename these files to the correct name, as they are from a backup that failed.
EDIT: Here is the full program. I renamed the variables to make more sense, so "codigo" is now "idcode".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int i, j, k;
char value1[26], value2[70], idcode[11], filename[16], fullname[64], filenamestring[16], fullnamestring[64];
// Opening file.
FILE *nomes;
nomes = fopen("/Users/EA/Desktop/Songs/backup.txt", "rt");
if(nomes == NULL)
{
printf("Erro ao abrir backup.txt");
exit(1);
}
// Skipping beggining of file until first value.
for(i=0; i<10; i++)
{
fscanf(nomes, "%*s");
}
// Reading first value, and repetition.
while(fscanf(nomes, "%s", value1) == 1)
{
j = k = 0;
// Extracting idcode from value1.
for(i=7; i<18; i++)
{
idcode[j] = value1[i];
j++;
}
// Filling the complete filename.
sprintf(filename, "%.*s.mp4", 11, idcode);
// Reading second value, the "human" filename.
fscanf(nomes, "\n%[^\n]", value2);
for(i=6; i<70; i++)
{
fullname[k] = value2[i];
k++;
}
// Transforming filenames into strings for rename function.
strncpy(filenamestring, filename, 16);
strncpy(fullnamestring, fullname, 64);
// Renaming the files.
rename(filename, fullname);
// Skipping useless data before the next cycle.
for(i=0; i<9; i++)
{
fscanf(nomes, "%*s");
}
}
// Closing file and ending program.
fclose(nomes);
return(0);
}
It looks like you got an array of char's.
You can simply do:
sprintf(filename, "%.*s.mp4", 11, codigo)
You can read more about the %.*s specifier in this question.
If you just want to append the format ".mp4" to the end of the string the easiest way to do that is just:
strcat(filename,".mp4");
after you printed the name without the ".mp4" into it.
If you really want to use sprintf then i think this should suffice:
sprintf(filename,"%s.mp4", codigo);
Also,if you want your string to be bigger and not fixed in size you can put "\0" at the end of it(this might not work if you try to use the strings in other programming languages but c) with strcat as above,or you can do this:
memset(&filename, 0, sizeof(filename));

Why does this function delete all the file data when I run it?

When I run the program and I want to delete a product code then this function deletes all the file.
Could you please help me?
void PRODUCT_delete()
{
int code;
FILE *stock=fopen("stock.dat","wb+");
printf("PLEASE TYPE THE CODE OF THE PRODUCT YOU WISH TO DELETE:\t");
scanf(" %d",& code);
printf("\n");
fseek(stock,0,SEEK_END);
int fl_size=ftell(stock);
int quantity= fl_size/sizeof(product);
rewind(stock);
prdct cprd= (product *)malloc (sizeof(product)*quantity);
assert(cprd);
prdct cprd1= (product *) malloc(sizeof(product)*quantity);
assert(cprd1);
fread(cprd1,sizeof(product),quantity,stock);
int i;
for(i=0;i<quantity;i++)
{
if(cprd1[i].code!=code)
{
cprd[i]=cprd1[i++];
}
else
{
continue;
}
}
fwrite(cprd,sizeof(product),quantity,stock);
fclose(stock);
free(cprd1);
free(cprd);
printf("\a THE PRODUCT DELETED!!!\n")
}
A few problems:
opening a file with wb+ truncates the file, you should probably use a new file for output and then rename afterwards
<was wrong, deleted>
you need to decrement quantity if you remove the product code
See:
http://man7.org/linux/man-pages/man3/fopen.3.html
http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx
w+ truncate the file. You should use r+
Apparently the b modificator is for windows (non-posix systems).

C programming opening and reading from a file

int main(void){
FILE *ifp; //input file pointer
int totalClock; //total clock count
// BEGIN OPERATIONS=============================
ifp=fopen("prog1.asy.txt", "r");
system("PAUSE");
assert(ifp!=NULL);
//populate the instMem with inst===================
int i=0;
//system("PAUSE");
for (i=0;i<512;i++)
{
inst temp=parser(ifp);
if (temp.opcode==-1)
break;
instMem[i]=temp;
printf("%s\n", instMem[i].rawCode);
}
printf("\n%d instructions parsed\n", i-1);
system("PAUSE");// PAUSE TO CHECK CODE PARSING IS CORRECT========
int cont=0;
while (cont==0){
//begin sim================================================
//initialize the mem=======================================
int i;
for (i=0;i<512;i++)
data[i]=0;
for (i=0;i<32;i++)
reg[i]=0;
IF_Time=0;
ID_Time=0;
EX_Time=0;
MEM_Time=0;
WB_Time=0;
//prompt input parameters===================================
printf("Memory access time: c=");
scanf("%d", &c);
printf("\nMultiply time: m=");
scanf("%d", &m);
printf("\nExecute time: n=");
scanf("%d", &n);
assert(c>0);
assert(m>0);
assert(n>0);
//start execution now that the program has been broken to unparsed strings====
while (0==0)
{
WB();
MEM();
if (MEM_WB.instruction.opcode==HALT)
break;
EX();
ID();
IF();
totalClock++;
system("PAUSE");
}
//PRINT RESULTS=============================================
printf("Run again with new parameters? 0=yes");
scanf("%d", &cont);
}
fclose(ifp);
system("PAUSE");
return 0;
}
struct inst parser(FILE *ifp){
char str[100];
struct inst temp;
if (fgets(str, 100, ifp)==NULL) {
inst temp={"NULL", -1,0,0,0};
}
else {
inst temp={str, 0,0,0,0};
puts(str);
}
return temp;
}
I am trying to read in a test file so that i can parse it into strings for analysis later. It opens the test file but it doesn't read the lines of test in the code. Is there something I am doing wrong.
Your parser functions only reads once from the file and does nothing with the result (since temp would be a local variable to the if branch, not to the function). First thing is to remove inst from inst temp = ... to see that it reads the first instruction. Then, you need to make that function loop over all lines in the file.
First of all, you need to format your source code on this page to make it more readable.
For parser(), I don't think you can return a structure. So please use a pointer instead. And, as Mihai mentions, "temp" is a temporary variable located on the stack, and it will be destroyed when returning from function parser().
I don't see the declarations of variables in the code snippet:
IF_Time=0;
ID_Time=0;
EX_Time=0;
MEM_Time=0;
WB_Time=0;
So I assume you could remove some unused code to make the question clear.
The last thing is: to analyze log files, shell scripts is more suitable than C. If you're not working on a UNIX/Linux box, you could also use Perl/Python if you want. They are all less error prone and easy to debug when used to analyze log files.

C Passing file pointer into a function

I have a problem with passing file pointers. How do I pass it if there is a function with a file pointer within a function(void writequest in my code)? It was working before I put in the void writequest. The program itself is supposed to read from one file that is filled with movie names and then put them into another. Of course, feel free to note any other failures in my code.
void writequest(int no)
{
int i, j, loop_ctrl, destination;
int movement;
char lib[loop_ctrl+1][92];
int write_nr[loop_ctrl], sorting[destination];
char searching[92];
char *c;
FILE *watched;
FILE *temp;
FILE *refrom;
FILE *reto;
FILE *towatch;
if(no==1)
{
printf("No match found.\n");
}
else if(no==0)
{
printf("Do you wish you write them into a file?\n1 - Yes\n0 - No\n");
scanf("%d", &j);
if(j==1)
{
tofile(watched, temp, refrom, reto, destination, loop_ctrl, write_nr, lib, movement);
close(towatch, watched, temp, refrom, reto);
remove("To_watch.txt");
rename("temp.txt", "To_watch.txt");
}
else if(j==0)
{
printf("Alright then\n");
close(towatch, watched, temp, refrom, reto);
}
}
}
char *c;
FILE *watched;
FILE *temp;
FILE *refrom;
FILE *reto;
FILE *towatch;
These are all pointers. So if you call upon them in your functions your asking for the value inside them. That's their address. except for movement. What is a bit strange.
It is vital to know what the functions exactly are before anyone can say what the problem is.

Using a function to read in a file

I have the code below which compiles fine in xcode, but when I take it across to Microsoft Visual studio I get a bunch of errors.
void openfile(int mapArray[MAX_HEIGHT][MAX_WIDTH], int *interest, int *dimension1, int *dimension2)
{
int counter = 0;
char buffer;
int rowss, colss;
*interest = 0;
FILE *f;
f = fopen(FILENAME, "r");
if (f==NULL) {
printf("Map file could not be opened");
return 0;
}
// create char array the dimensions of the map
fscanf(f, "%d %d" , dimension1, dimension2 );
// printf("%d %d\n" , dimensions[0], dimensions[1]);
// Reads the spaces at the end of the line till the map starts
buffer=fgetc(f);
while (buffer!='*') {
buffer=fgetc(f);
}
// Read the txt file and print it out while storing it in a char array
while (buffer!=EOF) {
mapArray[rowss][colss]=buffer;
colss++;
// Count up the points of interest
if (((buffer>64)&&(buffer<90))||(buffer=='#') ) {
counter++;
}
// resets column counter to zero after newline
if (buffer=='\n') {
colss=0;
rowss++;
}
buffer=fgetc(f);
}
// Closes the file
fclose(f);
*interest=counter;
}
Which parts are creating all the errors?
I get this list of errors when attempting to compile
Thanks in advance.
I see a few immediate problems. First, you're not initialising rowss or colss before you use them, hence they could contain any value.
Second, fgetc() returns an int so that you can detect end of file. By using a char to hold the return value, you're breaking the contract with the standard library.
Thirdly, you return a 0 if the filename couldn't be opened, despite the fact that the function is specified to return void (ie, nothing).
No doubt those are three of the errors the compiler picked up on, there may be others, and you should probably post the error list with your question for a more exhaustive analysis.

Resources