Cannot delete file in C - c

I am using Code Blocks and I would like to delete a file using C. The file is used by two functions but not simultaneously.
This is the first function which uses the file:
double FileRead()
{
double n,cl,cd,result;
FILE *fd;
char filename[] = "save.txt";
char buff[5024];
if ((fd = fopen(filename, "r")) != NULL)
{
fseek(fd, 0, SEEK_SET);
while(!feof(fd))
{
memset(buff, 0x00, 5024);
fscanf(fd, "%[^\n]\n", buff);
}
sscanf(buff, "%lf %lf %lf",&n,&cl,&cd);
printf("cl: %1.5f cd: %1.5f\n",cl,cd);
result = (cl/cd);
printf("The CL/CD ratio is : %1.5f\n",result);
}
else
result = 0;
fclose(fd);
return result;
}
And this is the second function:
void evaluate(void) /*evaluate the population */
{
int mem;
int i;
double x[NVARS+1];
char buffer[101] = "save.txt";
FILE *controlpoints;
double y[NVARS] = {1.00000,0.92544,0.82351,0.78301,0.74004,0.50199,0.40422,0.31056, /*fixed values on x axis */
0.18549,0.14954,0.11702,0.06331,0.02581,0.01334,0.00509,0.00000,0.00052,0.00555,0.03324,
0.11345,0.33088,0.43678,0.60146,0.70751,0.8043,0.92047,0.98713,1.00000};
for(mem = 0; mem < POPSIZE; mem++)
{
controlpoints = fopen("controlpoints2.txt","w");
for(i = 0; i < NVARS; i++)
{
x[i+1] = population[mem].gene[i];
fprintf(controlpoints,"%1.5f\n%1.5f\n",y[i],x[i+1]);
printf("The value of population[%d].gene[%d] is %f\n",mem,i,population[mem].gene[i]);
}
fclose(controlpoints);
rbspline();
XfoilCall();
population[mem].fitness = FileRead();
}
remove(buffer);
if(remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
fprintf(stderr, "Error deleting the file %s.\n", buffer);
}
All the time I am getting the message "Error deleting the file save.txt". Can you please check it out and tell me what am I doing wrong?

Your code in the second function contains:
remove(buffer);
if (remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
fprintf(stderr, "Error deleting the file %s.\n", buffer);
You're removing the file twice and the second time it isn't there, so you report failure.
Fix: remove the unchecked remove(buffer) line.

Look at this part of the code
remove(buffer);
if(remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
I think you want this
ret=remove(buffer);
if(ret==0)
printf("File %s deleted.\n", buffer);
else

Related

How to get all the content using fprintf in c

I'm trying to print all content of my file but I'm unable to print that to the filebut just first line is being printed, Suggest some way for the same.
First it was just printing 1 line when I hadn't used while loop
When I used while loop with !EOF condition then it didn't even get into while loop and thus was not printing any content.
static void
processNode(xmlTextReaderPtr reader) {
const xmlChar *name, *value;
FILE *fp = fopen("telemetryOutput.txt", "w+");
name = xmlTextReaderConstName(reader);
if (name == NULL)
name = BAD_CAST "--";
value = xmlTextReaderConstValue(reader);
fprintf(fp, "%s\n", "Testing");
// facing issue in this portion:
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
/////
if (value == NULL)
fprintf(fp, "\n");
else {
if (xmlStrlen(value) > 40)
fprintf(fp, " %.40s...\n", value);
else
fprintf(fp, " %s\n", value);
}
}
/**
* streamFile:
* #filename: the file name to parse
*
* Parse and print information about an XML file.
*/
static void
streamFile(const char *filename) {
xmlTextReaderPtr reader;
int ret;
reader = xmlReaderForFile(filename, NULL, 0);
if (reader != NULL) {
ret = xmlTextReaderRead(reader);
while (ret == 1) {
processNode(reader);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
if (ret != 0) {
fprintf(stderr, "%s : failed to parse\n", filename);
}
} else {
fprintf(stderr, "Unable to open %s\n", filename);
}
}
int main(int argc, char **argv) {
if (argc != 2)
return(1);
/*
* For creating file
*/
FILE *fptr = fopen("telemetryOutput.txt", "rb+");
char there_was_error = 0;
char opened_in_read = 1;
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("telemetryOutput.txt", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
streamFile(argv[1]);
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
// File Handling
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
return(0);
}
#else
int main(void) {
fprintf(stderr, "XInclude support not compiled in\n");
exit(1);
}
#endif
I have tried using below method but was unable to get required content
while(!EOF){
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
}
Your logic is wrong. Initially file pointer is at the EOF since the file is empty. Thus it doesn't get into the loop itself.
If you have to print to file only 1 line don't use that condition for while loop.
Also open file in append mode otherwise it might overwrite from start each time you write on it.

How to read a file into an array of structs?

Im trying to read a text file into an array of structs, but when trying to print the array, the struct is empty. The printing function works fine and I think the problem is in getRawData.
struct student
{
char ID[MAXID + 1];
char f_name[FIRST_NAME_LENGTH + 1];
char s_name[LAST_NAME_LENGTH + 1];
int points[MAXROUNDS];
};
//main//
case 'W':
if(save(array, len) == 0);
{
printf("Data saved.\n");
}
break;
case 'O':
if(getRawData(array, len));
{
printf("File read.\n");
}
break;
int save(struct student *h, int num_students)
{
char name[20];
printf("Enter file name: " );
scanf("%s", name); // Read in filename
FILE *output = fopen(name, "w"); // open the file to write
if (!output) {
return -1; // error
}
for (int i = 0; i < num_students; ++i)
{
fprintf(output, "%s %s %s \n", h[i].f_name, h[i].s_name, h[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fprintf(output, "%d\n", h[i].points[j]);
}
printf("Information of student %s %s (%s) written into file %s\n", h[i].s_name, h[i].f_name, h[i].ID, name);
}
fclose(output); // close
return 0;
}
int getRawData(struct student *records)
{
int i;
int nmemb; // amount of structs
char name[20];
printf("Name of the file to be opened: \n");
scanf("%s", name);
FILE *outtput = fopen(name, "r");
int ch=0;
int lines=0;
if (outtput == NULL);
return 0;
lines++;
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
{
lines++;
}
}
nmemb = lines / 7;
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fscanf(outtput, "%d\n", &records[i].points[j]);
}
}
printf("%d", lines);
return i;
}
So my goal is to get the data from the file and write it over whatever there is stored in the struct array. I would appreciate some help as I have been working on this for way too long.
Look at this code in getRawData(), first you are reading file to identify total number of lines:
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
.....
.....
due to this the file stream pointer pointing to EOF and after this, in the for loop, you are doing:
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
.....
.....
Here, the fscanf() must be returning the EOF because there is nothing remain to read from stream file. You should check the return value of fscanf() while reading file.
You should reset the pointer to start of file before reading it again. You can use either rewind(ptr) or fseek(fptr, 0, SEEK_SET). Below is a sample program to show you what is happening in your code and how the solution works:
#include <stdio.h>
int main (void) {
int ch;
int lines = 0;
char str[100];
FILE *fptr = fopen ("file.txt", "r");
if (fptr == NULL) {
fprintf (stderr, "Failed to open file");
return -1;
}
while (!feof(fptr)) {
ch = fgetc (fptr);
if(ch == '\n') {
lines++;
}
}
printf ("Number of lines in file: %d\n", lines);
printf ("ch : %d\n", ch);
printf ("Now try to read file using fscanf()\n");
ch = fscanf (fptr, "%s", str);
printf ("fscanf() return value, ch : %d\n", ch);
printf ("Resetting the file pointer to the start of file\n");
rewind (fptr); // This will reset the pointer to the start of file
printf ("Reading file..\n");
while ((ch = fscanf (fptr, "%s", str)) == 1) {
printf ("%s", str);
}
printf ("\nch : %d\n", ch);
fclose (fptr);
return 0;
}
The content of file reading in the above program:
Hello Vilho..
How are you!
Output:
Number of lines in file: 2
ch : -1
Now try to read file using fscanf()
fscanf() return value, ch : -1
Resetting the file pointer to the start of file
Reading file..
HelloVilho..Howareyou!
ch : -1
Here you can see, the first ch : -1 indicate that the file pointer is at EOF and if you try to read you will get EOF because there is nothing left to read. After resetting file pointer, you can see fscanf() is able to read file.
You should not use while (!feof(file)). Check this.

C Programming - Difficulty with Parsing a Temp Folder

I'm having some trouble with parsing a temp.txt folder which contains the basenames of various files in a directory. I'd like to sort through this file, figure out what each of the file types are line by line, and then delete them from the temp file. I have been able to do carry out the parsing of the file names to discover their type, but when I call my delete function... it only works for some of the files and leaves behind some junk occasionally.
The input file looks like this:
temp.txt input
The output file after running looks like this:
temp.txt output
#include < stdio.h >
#include < string.h >
#include < unistd.h >
#include < stdlib.h >
/* This program module parses through the temp.txt file and finds .gif, .png, and .bmp files
and prints to standard output their file type in the order in which they're found.
It also takes all the files that aren't of those three types and puts them in a junk file.
*/
int deleteline(int delete_line);
int main(int argc, char * argv[]) {
FILE * file = fopen("temp.txt", "r"); /* should check the result */
FILE * myfile = fopen("junkfiles.txt", "w");
char line[4069];
char * gif = ".gif";
char * png = ".png";
char * bmp = ".bmp";
int i = 0;
int j = 0;
// if tempfile cannot be created, error handle
if (!file) {
puts("Some kind of file error!");
return 1;
}
// if junkfile cannot be created, error handle
if (!myfile) {
puts("Some kind of file error!");
return 1;
}
while (fgets(line, sizeof(line), file)) {
i++;
if (strstr(line, gif) != NULL) {
j = deleteline(i);
fflush(NULL);
if (j == 0) {
printf("File on line %d is: ", i);
puts(line);
printf("This is a .gif\n\n");
} else {
printf("Some error on line %d\n", i);
}
} else if (strstr(line, png) != NULL) {
j = deleteline(i);
if (j == 0) {
printf("File on line %d is: ", i);
puts(line);
printf("This is a .png\n\n");
} else {
printf("Some error on line %d\n", i);
}
} else if (strstr(line, bmp) != NULL) {
j = deleteline(i);
if (j == 0) {
printf("File on line %d is: ", i);
puts(line);
printf("This is a .bmp\n\n");
} else {
printf("Some error on line %d\n", i);
}
} else {
j = deleteline(i);
if (j == 0) {
printf("The file on line %d is junk.\n\n", i);
} else {
printf("Some error on line %d\n\n", i);
}
fprintf(myfile, "%s", line);
}
}
/* may check feof here to make a difference between eof and io failure -- network
timeout for instance */
fclose(file);
fclose(myfile);
fflush(NULL);
return 0;
}
int deleteline(int delete_line) {
FILE * fileptr1, * fileptr2;
char * filename = "temp.txt";
char ch;
int temp = 1;
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
//rewind
rewind(fileptr1);
//open new file in write mode
fileptr2 = fopen("replica.txt", "w");
while (ch != EOF) {
ch = getc(fileptr1);
if (ch == '\n')
temp++;
//except the line to be deleted
if (temp != delete_line) {
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file replica.c to original name
rename("replica.txt", filename);
return 0;
}

C using a file as an argument

The problem I am having is that whenever I run the code I get the Null value for myfile before I even get to pass the file name as the argument into the program and i'm not sure why any help is much appreciated.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE* myFile; // file pointer
myFile = fopen(argv[1] , "r"); //open file
if(myFile==NULL)
{
printf("Can't Open FIle.\n"); // if file doesn't exist then exit
exit(0);
}
int A[10000]={0};
int B[10000]={0};
double C[10000]={0};
int N,M;
int i=0;
fscanf (myFile, "%d", &N); //input N from file
printf("%d\n",N);
if(N>100)
{
exit(0); // if N>100 then exit
}
while (!feof (myFile)) // loop until file pointer reaches to the end of file
{
fscanf (myFile, "%d", &A[i]); //input source
fscanf (myFile, "%d", &B[i]); // input destination
fscanf (myFile, "%lf", &C[i]); // input time
i++;
}
fclose (myFile); //close file
M=i; // number of lines = M
for (i = 0; i < M; i++)
{
if(A[i]==0) //end of output
break;
else
{
printf("%d %d %lf:\n",A[i],B[i],C[i]); //print source, destination and time
if(A[i]>=1&&A[i]<=N)
{
if(B[i]>=1&&B[i]<=N)
{
if(A[i]==B[i])
{
printf("Error:Source city is the same as destination city.\n"); //same source and destination error:condition
}
else
{
if(C[i]<0)
{
printf("Error:Invalid Time.\n"); //invalid time
}
else
{
//
}
}
}
else
{
printf("Error: Invalid destination city.\n"); //invalid destination condition
}
}
else
{
printf("Error: Invalid source city.\n"); //invalid source condition
}
}
}
return 0;
}
If you don't pass a file name as an argument to the program, the contents of argv[1] are undefined.
Since anything could be there in argv[1] when the program attempts to open the file, the most probable thing is that there is no file with that name, and hence fopen() returns NULL.
You should not try to access command line arguments without checking that they were supplied, for that check argc, if you just expect 1 argument, then a simple check would be
char filename[256]; /* the size should be reasonable
* can be PATH_MAX or MAX_PATH,
* depending on whether it's Windows
* or not
*/
if (argc < 2)
{
size_t length;
fprintf(stdout, "Error: %s program expects one argument\n", argv[0]);
fprintf(stdout, "Please input the file name: ");
if (fgets(filename, sizeof(filename), stdin) == NULL)
{
fprintf(stdout, "Error: unexpected error\n");
return -1;
}
length = strlen(filename);
if (length == 0)
{
fprintf(stdout, "Error: the provided file name is invalid.\n");
return -1;
}
if (filename[length - 1] == '\n')
filename[length - 1] = 0;
}
else
strcpy(filename, argv[1]);

C - Writing to binary failed (rewrites a file)

I'm not sure what I'm doing wrong, trying to write a simple program that encrypts after being ran once renames. When the method is ran twice it is supposed to do the same thing but instead it decrypts the file. The first version worked but it left the old version and made a new version and I wanted a program that I could run once to encrypt and again to decrypt allowing me to change the file extension in the process, for convenience.
When I run the program it crashes on fwrite().
#include <stdio.h>
#include <stdlib.h>
#define KEY '&'
int main(void)
{
FILE *fp; // file pointer
size_t size, test; // file size
char src_file[FILENAME_MAX], dst_file[FILENAME_MAX];
int orig_char, new_char;
int i = 0;
printf("Enter the name of the source file \"file.ext\": ");
scanf("%s", src_file);
if ((fp = fopen(src_file, "rb")) == NULL) { // open file
fprintf(stderr, "Can't open \"%s\"\n", src_file);
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END); // find the end of file
size = ftell(fp); // file size
fseek(fp, 0, SEEK_SET); // set file position to start
unsigned char buffer[size], *temp = buffer; //buffer
test = fread(buffer, sizeof(buffer[0]), size, fp);
printf("size written: %d, size of file: %d\n", test, size);
if (test != size) {
fprintf(stderr, "Error: operation fwrite failed!\n");
exit(EXIT_FAILURE);
}
fclose(fp);
printf("Enter the name of the destination file \"file.ext\": ");
scanf("%s", dst_file);
if ((fp = fopen(src_file, "wb")) == NULL) {
fprintf(stderr, "Can't open \"%s\"\n", dst_file);
exit(EXIT_FAILURE);
}
puts("Test1");
for (i = 0; (size_t)i < size && orig_char != EOF; i++, temp++) {
orig_char = (int) *temp;
new_char = orig_char ^ KEY;
*temp = new_char;
}
puts("Test3");
test = fwrite(buffer, sizeof(buffer[0]), size, fp);
fclose(fp);
free(buffer);
if ((rename(src_file, dst_file)) != 0)
fprintf(stderr, "Failed to rename file, make sure file doesn't" \
"already exist!\n");
return 0;
}
Here is my final code in case anyone else comes across this problem, I cleaned it up a tad and added a loop feature for offsetting multiple files. I also added some error recovery.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define KEY '&'
int main(void)
{
FILE *fp; // file pointer
size_t size, test; // file size
char src_file[FILENAME_MAX], dst_file[FILENAME_MAX];
char ch = 'Y';
int orig_char, new_char;
int i = 0;
while (toupper(ch) != 'N') {
printf("Enter the name of the source file \"file.ext\": ");
scanf("%s", src_file);
while ((fp = fopen(src_file, "rb")) == NULL) { // open file
fprintf(stderr, "Can't open \"%s\"\n", src_file);
printf("Enter the name of the source file \"file.ext\": ");
scanf("%s", src_file);
}
fseek(fp, 0, SEEK_END); // find the end of file
size = ftell(fp); // file size
fseek(fp, 0, SEEK_SET); // set file position to start
unsigned char buffer[size], *temp = buffer; // buffer
// send file to buffer
test = fread(buffer, sizeof(buffer[0]), size, fp);
printf("size written: %d, size of file: %d\n", test, size);
if (test != size) {
fprintf(stderr, "Error: operation fwrite failed!\n");
system("Press any key to continue");
exit(EXIT_FAILURE);
}
fclose(fp);
while ((fp = fopen(src_file, "wb")) == NULL) {
fprintf(stderr, "Can't open \"%s\"\n", src_file);
printf("Enter the name of the source file \"file.ext\": ");
scanf("%s", src_file);
}
// offset buffer data
for (i = 0; (size_t)i < size && orig_char != EOF; i++, temp++) {
orig_char = (int) *temp;
new_char = orig_char ^ KEY;
*temp = new_char;
}
// write buffer to file
test = fwrite(buffer, sizeof(buffer[0]), size, fp);
fclose(fp);
printf("Enter the file's new name \"file.ext\": ");
scanf("%s", dst_file);
while ((rename(src_file, dst_file)) != 0) {
fprintf(stderr, "Failed to rename file, make sure file doesn't already exist!\n");
}
printf("size written: %d, size of file: %d\n", test, size);
printf("File Successfully offset\n\n");
printf("Would you like to continue: ");
scanf(" %c", &ch);
}
return 0;
}

Resources