Not able to open a file in read mode in c - c

char fileName[20];
puts("Enter the date.\n");
scanf("-> %s", fileName);
//Read the file
FILE *ptr;
ptr = fopen(fileName, "r");
if(ptr == NULL)
{
printf("\nNo file was found with this name\n");
exit(0);
}
else
{
printf("\nI FOUND the file.\n");
}
fclose(ptr);
I just want the user to enter a file name and then display 'found the file' as of now however even when the this code file and the text file are in same directory I am always getting the message'No file was found with this name' and I assure you that I am inputting the right file name(along with .txt extension).

Thank you #kaylum I got the answer.
The problem is with the scanf() statement. The scanf("-> %s", fileName) statement wants the user to input only -> otherwise it will fail.

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 fix segmentation error in C programming?

I want to get the user input to open a txt file but I'm getting this compilation error called. [1] 85501 segmentation fault can someone help me with this? A sample input 2021-10-17
Here's git repo https://github.com/anjula-sack/diary
void DecryptEntry()
{
FILE *fptr;
char filename[20];
printf("Please enter the date of the entry you want to read, ex:2021-10-17\n");
fscanf(stdin, " ");
fgets(filename, 20, stdin);
strcpy(filename, ".txt");
printf("%s.txt", filename);
if ((fptr = fopen(filename, "r")) == NULL)
{
printf("Error! the entry doesn't exist");
}
}
Looking at the actual code from your github link, then you have this:
strcpy(filename, ".txt");
if ((fptr = fopen(filename, "r")) == NULL)
{
printf("Error! the entry doesn't exist");
}
fgets(message, 100, fptr);
First of all the strcpy is nonsense since it overwrites the filename and replaces it with ".txt". Since that is never a valid file name, fopen will always fail. And when it fails, you print an error message but continue execution, so the next fgets call will cause the crash.
Fix this by allocating enough space for filename, replace strcpy (overwrite) with strcat (append) and do a return etc upon failing to open the file.
You could easily have found these bugs yourself by single-stepping through the function using a debugger.

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)

need help My Library project has member problem

seems something is wrong. I've made a library project but some functions seem to be malfunctioning
for example : When i choose my member list (Shown below) it exists the code.
in c version.
void addmember()
{
system("cls");
// creating a FILE variable
FILE *fptr;
// creating a character variable
char ch;
// open the file in write mode
fptr = fopen("username.txt", "w");
// take user input
printf("Enter your name: ");
ch = getchar();
printf("Save any more?(Y / N):");
if(getch()=='n')
mainmenu();
else
system("cls");
addmember();
}
void memberlist(){
char ch;
FILE *fptr;
// open the file in read mode
fptr=fopen("username.txt", "r");
// display the content of the file
printf("\nFile content:\n");
while( (ch = getc(fptr)) != EOF ) {
printf("%c", ch);
}
printf("\nEnd of file\n");
// close file
fclose(fptr);
return 0;
}
In memberlist do you check if the fopen works well ? Probably fptr is NULL
Several remarks in addmember() :
addmember call itself at the end of its body, unconditionally, it is an infinite recursion
for each recursive call you fopen("username.txt", "w"); and that for nothing, but you never close the file
only one character is read for the name, it's suspicious

Writing to a file within a folder in C

How can I do this?
I know opening a new file is something akin to this:
fpcon=fopen("konf_in","w");
printf("Whatever I want to input");
fclose(fpcon);
The output file only needs to be a simple .txt or .dat file
To write to a file, you need to call fprintf and pass your file pointer which is fpcon, see this example:
char name[20];
int number;
FILE *f;
f = fopen("/your_folder/sample.txt", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("\nNew contact name (max 19): ");
fgets(name, sizeof(name), stdin);
printf("New contact number: ");
scanf("%d", &number);
fprintf(f, "%s - %d\n", name, number);
fclose(f);
This page gives you further intel on how to handle file writes, appends, etc.
Just for clarification, the allowed modes for fopen are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)

Resources