Can anyone tell me why am i getting this error...? - c

Here is a C Project. I am working with text and binary files. This is a project that reads from stdin a file and also reads a new file and writes the information that the existed file has to the new file. But i get an error .This is my code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fFrom;
FILE *fTo;
char filename[80];
char newfilename[80];
printf("Enter the file you want to copy: ");
scanf("%s", filename);
fFrom = fopen(filename, "r");
if(fFrom == NULL)
{
printf("File not found...");
return;
}
printf("Enter new filename: ");
scanf("%s", newfilename);
fTo = fopen(newfilename, "r");
if(fTo)
{
printf("File already exists...\n");
return;
}
fclose(fTo);
fTo = fopen(newfilename, "w");
if(!fTo)
{
printf("Error opening file...\n");
return;
}
while (!feof(fFrom))
{
fputc(fgetc(fFrom), fTo);
}
fclose(fFrom);
fclose(fTo);
return;
}
Then In the console:
Enter the file you want to copy: test.txt // existing file
Enter new filename: new_test.txt // new file
Segmentation fault (core dumped)

The seg fault is likely coming from the first call to fclose(fTo) when fTo is null (file doesn't exist).
See this answer for more discussion on calling fclose with a null FILE* pointer.

Related

how to copy a file another directory in c [duplicate]

This question already has answers here:
copy file function in C
(2 answers)
Closed last year.
#include <stdio.h>
#include <stdlib.h>
void main(){
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
printf("\n Program to copy a file in another name: \n");
printf("Enter the source file name: ");
scanf("%s", fname1);
fptr1 = fopen(fname1, "r");
if (fptr1 == NULL){
printf("File does not found or an error occured when opening!!");
exit(1);
}
printf("\n Enter the new file name: ");
scanf("%s", fname2);
fptr2 = fopen(fname2, "w");
if( fptr2 == NULL){
printf("File does not found or an error occured when opening!!");
fclose(fptr1);
exit(2);
}
while(1){
ch = fgetc(fptr1);
if(ch == EOF){
break;
}
else{
fputc(ch, fptr2);
}
}
printf("The file %s copied to file %s succesfully.\n", fname1, fname2);
fclose(fptr1);
fclose(fptr2);
}
That is the code I copy a file. Actually, my purpose is to move a file to another directory so I was think first I should copy the file then delete the source file. I am also open to better solutions.
Re "open to better solutions", if the goal is just to get the file moved from within a C program, and not necessarily to directly program it instruction-by-instruction in C, then I'd just use popen(), something like...
int moveme(char *source, char *target) {
int status=0;
FILE *fp=NULL;
char command[999];
sprintf(command,"mv %s %s",source,target);
if ((fp=popen(command,"r")) != NULL) {
pclose(fp); status = 1; }
return (status);
} /* --- end-of-function moveme() --- */
And that'll likely be more efficient than anything you can directly program yourself, especially if it's a large file. The operating system will probably just change some directory entries. Won't even directly touch the file itself.

How to allow other sentences to be in a file?

In this code whenever I write a new sentence, it replaces the previous sentence in a file that I put earlier. I want to not replace the previous sentence and also allow other sentences in that file line after line.
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
// creating file pointer to work with files
FILE *fptr;
// opening file in writing mode
fptr = fopen("file.txt", "w");
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
Open the file in append mode.
fptr = fopen("file.txt", "a");
https://en.cppreference.com/w/c/io/fopen

File Pointer Not Being Assigned a Value When Using fopen()

I am trying to write a simple C program which will read data from a csv file and perform some calculations on this data.
Unfortunately I have a problem where a file pointer of mine, fptr , is not being assigned a value after calling fopen(). I know this is the case after stepping through VS 2017's debugger. Yet I do not know why this is the case. This is a huge problem and means my program will throw some very nasty exceptions any time I try to read data from the file or close the file.
My code is below:
main.c
#include<stdio.h>
#include <stdlib.h> // For exit() function
#include"constants.h" //For access to all project constants
/***************************************************************************************************************
To keep the terminal from automatically closing
Only useful for debugging/testing purposes
***************************************************************************************************************/
void preventTerminalClosure() {
//flushes the standard input
//(clears the input buffer)
while ((getchar()) != '\n');
printf("\n\nPress the ENTER key to close the terminal...\n");
getchar();
}
/***************************************************************************************************************
Read the given input file
***************************************************************************************************************/
void readInputFile(char fileName[]) {
FILE *fptr;
char output[255];
//open the file
if (fptr = fopen(fileName, "r") != NULL) { //read file if file exists
//fscanf(fptr, "%[^\n]", output);
//printf("Data from the file:\n%s", output);
printf("<--Here-->");
}else {
printf("\nERROR 1: File %s not found\n", fileName);
preventTerminalClosure();
exit(1);
}
fclose(fptr); //close the file
}
/***************************************************************************************************************
* * * Main * * *
***************************************************************************************************************/
void main() {
char testName[MAX_NAME_SIZE];
printf("Hello World!\n");
printf("Please enter your name: ");
scanf("%s", testName);
printf("It's nice to meet you %s!", testName);
readInputFile("dummy.txt");
preventTerminalClosure(); //Debug only
}
I have made sure that my fake file does indeed exist and is located in the correct location. Otherwise my code would hit the else block inside of readInputFile(). That is something I have thoroughly tested.
There is clearly something basic that I am missing which explains this pointer behavior; but what that is, I am not sure. Any help would be appreciated! :)
Use parenthesis to enforce order, so that fptr is compared against NULL after it has been assigned value returned by fopen:
FILE *fptr;
char output[255];
//open the file
if ( (fptr = fopen(fileName, "r")) != NULL)

How to write data to multiple files using arrays of pointers of file in C?

This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}

Copy from one txt file to another with c

I am having problems with copying txt files. I need to info from one file to another.
My code looks like this,
_tprintf (TEXT("%s\n"), FindFileData.cFileName);
memset(fileName, 0x00, sizeof(fileName));
_stprintf(fileName, TEXT("%s\\%s"), path, FindFileData.cFileName); //iegust
FILE *fptr = fopen(fileName, "r");//atver
fscanf(fptr,"%[^\n]",c); //iegust datus no faila
printf("Data from file:\n%s",a);
strcpy(a, c); //nokope datus
buffer2 = strtok (c, ","); //norada partraukumu un tadas lietas
while (buffer2) {
buffer2 = strtok (NULL, ",");
if(i<1){ printf("%s\n", c);}
i++;
while (buffer2 && *buffer2 == '\040'){
buffer2++;
// TODO ieliec iekavinas
}
}
And after that I use basic fputs().
My problem is that this code ignores new lines. It prints out fine, each string in it's own line, but that does not happen in file. (\n).
Your problem is that you just need to copy information from one file to another. So, why you don't use a simple solution to do it than your. I have a snipet code can solve your problem easily as shown below.
If I am wrong about your question, please give me advices.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}

Resources