C Program - File-io user input - c

I am trying to get a user to enter a specific file name and have the program be able to read it.
FILE *fp;
char file[10];
fgets(file, sizeof(file), stdin);
fp = fopen(file, "r");
if (fp == NULL) {
printf("File doesn't open\n");
return 1;
}
This is a section of my code and what i'm currently trying to do. When i run the program and enter the file name, the output is "File doesn't open" which is my error message.

The problem is that fgets also incorporates the newline character '\n' in the string read. You need to remove it,
char* p;
if(p = *strchr( file, '\n' ))
*p = '\0';
otherwise fopen will fail.

Assuming you meant fopen(file,...), before you can do that you must strip file of a newline. See man pages for fgets and [I suggest] strchr.

Use perror to print system error diagnostics:
int main(){
FILE *fp;
char file[10];
fgets(file, sizeof(file), stdin);
fp = fopen(file, "r");
if (!fp) {
perror(file);
return 1;
}
}
If you ask for file f, it'll print:
f
: No such file or directory
which should point you at the source of the problem (the fopen call may also fail for permissions reasons, for example).

Related

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.

fopen give me a segementation fault

I'm trying to open the output_voice_capture.txt but it gives me a segementation fault, not only the file exists but it has read privilege.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fPtr;
char ch;
/*
* Open file in r (read) mode.
*/
printf("Opening file ......\n");
fPtr = fopen("/flash/etc/output_voice_capture.txt", "r");
if(fPtr == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading file contents character by character.\n");
do
{ printf("Read single character from file ......\n");
/* Read single character from file */
ch = fgetc(fPtr);
/* Print character read code ASCII on console */
printf ("%d \n", ch);
} while(ch != EOF); /* Repeat this if last read character is not EOF */
printf("Closing file ......\n");
fclose(fPtr);
return 0;
}
I am using minicom which contains all the bin that I can use , the problem is that when I use linux terminal and a simple .txt test file the code works just fine.
As Zaboj Campula already said in his comment EOF is defined as an integer of -1. On some systems a char is a value from 0..255, on others from -127..128. To avoid any problems one should use the feof() function (link) to check the end of the stream. This might be the source of your problem due to the different sizes of char and int.
Your code will print "File opened successfully. Reading file contents character by character." for each character read.
Leave functions only at one place: at the end. This makes your code much more readable
When parts of your code depend on something, enclose it with an error check.
Try this code:
int main() {
FILE * fPtr;
char ch;
int result = 0;
printf("Opening file ......\n");
if (!(fPtr = fopen("/flash/etc/output_voice_capture.txt", "r")) {
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
result = EXIT_FAILURE;
} else {
printf("File opened successfully. Reading file contents character by character.\n");
while (EOF != (ch = fgetc(fPtr))) {
printf ("%d \n", ch);
}
fclose(fPtr);
}
return result;
}

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)

When does fgets stop reading a line?

I am debugging my program using gdb, fgets(line, sizeof(line), fp2) reads nothing from a text file. so the program loops infinity ins side while(!feof(fp2)) and the EOF is never met i dont know why?
I'm putting part of the code for context,
here is the inputfile:
COPY START 1000
FIRST STL RETADR
CLOOP JSUB RDREC
LDA LENGTH
COMP ZERO
JEQ ENDFIL
ZERO WORD 0
RETADR RESW 1
LENGTH RESW 1
BUFFER RESB 4096
RSUB
END FIRST
here is the main program:
int main(int argc, char *argv[])
{
FILE *fp, *fp2, *fphex;
char line[1000] = "" ;
if (argc != 2)
{
printf("Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((fp = fopen(argv[1], "r")) == NULL)
{
printf("Can't open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
fp2 = fopen("intermediate.asm", "w");
fp2 = removecomment(fp,fp2);
rewind(fp2);
while (!feof(fp2))
{
fgets(line, sizeof(line), fp2); /*this fgets reads only 4 bytes of empty spaces*/
parse(line);
}
struct node *print = head;
fphex = fopen("Hex_code", "w");
while(print == NULL)
{
fprintf(fphex, "%s", print->instruction);
print = print->next;
}
return(0);
}
EDIT:
While(!feof(File*pointer) was not the problem.
i was trying to read from a write only fopen file.
i resolved it by fclose(file) fopen("file","r")
or as suggested by others w+ mode.
I think closing and opening in read mode is safer.
Ok, here is the problem, you have "w" as a file opening mode.
fp2 = fopen("intermediate.asm", "w");
it should be
fp2 = fopen("intermediate.asm", "r");
file opening modes are
w - write (file is deleted if exists)
r - read (file must exist)
a - append
than you have + sign which means:
w+ - write and read (overwrite if file exists)
r+ - read and write (file must exist)
a+ - append and read (create file if it does not exist)
fp2 was opened in write mode "w", So it must be closed then opened in read mode "r" so lines could be read properly, people could have spotted that instead of saying its the While(!feof(fp2)).
I believe this is well addressed here, it will solve if you replace while(!feof(fp2)) ---> while(!feof(fp2) && !ferror(fp2))

C - fopen text file after building - OpenWRT - opkg

I have these lines in my C program:
int main(int argc, char **argv) {
int i=0, p=0;
FILE* fp;
fp = fopen("jacina.txt", "w+");
fscanf (fp, "%d", &i);
if (ftruncate(fp, 0) == -1) {
perror("Could not truncate")
};
p = i+10;
fprintf(fp, "%d", p);
}
After building this code to OPKG in OpenWRT (from Ubuntu), how can I read and write to this textual file which is located on any disk location where is located this OPKG?
Your code doesn't make any sense. To write the input given by user to a file:
Create a file first. Take input from user (say any string) and write it to the file with the help of file descriptor (fp) and close the file so that all buffers get flushed.
FILE *fp;
char comment[100] = {0};
fp=fopen("tempfile.txt","w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
printf("Enter String: ");
gets(comment);
fwrite(comment, sizeof(comment), 1, fp) ;
fclose(fp);
fprintf() too can be used instead to write data into a file.
Similarly to read from a file you can use fgets() or fread() to store the contents of the file in a buffer and display the contents of the file. Hope it helps.

Resources