Here is my code.
#include<stdio.h>
int main(int argc,char** argv)
{
FILE* fp;
fp=fopen(argv[1],"r");
struct element{
int value;
char activity;
};
typedef struct element element;
element a;
printf("%d",feof(fp));
}
Now if I don't give the last printf command it does not give me a segmentation fault, but if I give it printf it gives me a seg fault. Why?
I got the answer to my prev problem, now i have another problem
i had .txt appended to my input file in my makefile. Now i have another problem. on command make it gives error.
0make: *** [a.out] Error 1
why?
Check the return value of fopen (well, check the return value of any call), it probably failed to open the file.
Because you do not specify the file in a command line arguments, or because the file you have specified there could not be opened for some reason. In that case, fopen returns NULL, and when you pass that NULL to feof it crashes the program. You have to check return values and error codes, especially when functions may return NULL.
The correct code may look something like this:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE *fp;
if (argc < 2)
{
fprintf (stderr, "Please specify the file name.\n");
return EXIT_FAILURE;
}
fp = fopen(argv[1], "r");
if (fp == NULL)
{
perror ("Cannot open input file");
return EXIT_FAILURE;
}
printf ("%d\n", feof (fp));
return EXIT_SUCCESS;
}
Related
This question already has answers here:
If file pointer is null, do I have to use fclose()? (C)
(2 answers)
Closed 4 years ago.
I'm having always the error "Segmentation fault (core dumped)"" every time I try this a function:
int CheckFile(char * filename){
FILE * bd = fopen(filename, "r");
if(bd == NULL){
fclose(bd);
return -1;
}else{
fclose(bd);
return 0;
}
}
function calls:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_FILE_NAME "file.txt"
int CheckFile(char * filename);
int main(int argc, char ** argv[]){
char * name_of_file == NULL;
if(argc > 1){
printf("argc > 1\n");
for(i=0;argc>i;i++){
if(strcmp(argv[i],"-f")==0){
name_of_file = argv[i+1];
if(CheckFile(name_of_file) != 0)
printf("Can't find the file "%s".", name_of_file);
}
if(name_of_file == NULL){
if(CheckFile(DEFAULT_FILE_NAME) != 0);
printf("Can't find the default file \""DEFAULT_FILE_NAME"\".");
}
}
By my troubleshoots I would say the problem is on "char * filename", but can't find a way out of this. Can someone give me a hand? I would be thankful.
This has undefined behavior and should be expected to crash or worse:
if(bd == NULL){
fclose(bd);
A null pointer is not a valid argument to fclose. Just remove the call to fclose there.
The code doesn't compile properly. The definition of main() is wrong:
int main(int argc, char ** argv[]) {
It needs to be
int main(int argc, char **argv) {
Also this
char * name_of_file == NULL;
Needs to be
char * name_of_file = NULL;
Because we're doing initialization here, not comparison.
Also, that print doesn't compile for me either:
printf("Can't find the file "%s".", name_of_file);
It seems like your escape sequences/format specifiers got mangled somehow. Try
printf("Can't find the file %s.", name_of_file);
Instead.
Next, i isn't defined. Do you have it as a global variable that you haven't shown in your snippet? Either way you can just put it here:
for (int i = 0; argc > i; i++) {
instead of
for(i=0;argc>i;i++){
Also, this if here does nothing:
if(CheckFile(DEFAULT_FILE_NAME) != 0);
Because of that semicolon at the end, you probably want to remove that.
Last but not least, there are two } missing at the end of your main function.
It seems like you have problems with debugging your code. Consider using an IDE that will show you compilation errors. Also, you should not try to fclose the file if it didn't open (fopen returning NULL).
#include <stdio.h>
#include <stdlib.h>
struct fileIndex{
char name;
int key;
} index1;
int main(int argc, char *argv[]){
int i;
FILE *pFile;
pFile= fopen("cat/home/sysadmin/deneme.txt","r");
for(i=0; i<10; i++){
printf("%c",fgetc(pFile));
}
fclose(pFile);
}
When I want to run my program, it gives that error. I looked so long for a wrong line in code, but I didn't find any. Can you help me ?
If the file failed to open, that will make pFile equal NULL, which can easily cause fgetc() to segfault.
You must check for this before trying to read from the file:
if (pfile == NULL)
{
perror("Failed to open file");
exit(1);
}
change your code as
int i;
FILE *pFile;
pFile= fopen("cat/home/sysadmin/deneme.txt","r");
if(!pFile)
return;
Also.. looks like you file path is misplaced... are your meant t ouse /cat/home/sysadmin/deneme.txt
Is cat your current directory or part of absolute path
How come when I type in "(filename).txt" as part of one of the argument in terminal my code doesn't run and gives me a segmentation fault (core dumped)? but if I type "(filename)" instead then the code runs perfectly?
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv){
FILE *inFile = fopen(argv[1], "r");
FILE *outFile = fopen(argv[2], "w+");
char ch = fgetc(inFile);
while(ch != EOF){
fputc(ch, outFile);
ch = fgetc(inFile);
}
}
I skipped error checking writing this small sample code of what I mean. Terminal input would be
"./(program name) (filename).txt (filename2).txt" but this produces a segmentation fault (core dumped)
Whereas, if I type this in
"./(program name) (filename) (filename2) without the .txt file extension the code runs
If you put a debug statement as the first thing in your program printing the contents of argv[1] and argv[2] then you will be able to see the problem and we won't have to guess exactly what you are trying to do. It is very hard for us to understand this issue with a MCVE because you are opening files that exist on your computer but which might not exist on ours. So it could crash on your machine, but have some different error on mine.
"I skipped error checking" ... well that's fine when things work, but here something is going wrong: why not check the return codes and print out the error if there is one. For example:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv){
FILE *inFile;
FILE *outFile;
if (argc < 3) {
fprintf("Only got %d arguments!\n", argc);
exit(1);
}
printf("arg1: %s, arg2: %s", argv[0], argv[1]);
inFile = fopen(argv[1], "r");
if (inFile == NULL) {
perror("Failed on in file: ");
exit(1);
}
outFile = fopen(argv[2], "w+");
if (outFile == NULL) {
perror("Failed on out file: ");
exit(1);
}
int ch = fgetc(inFile); /*as per comments this should be int */
while(ch != EOF){
fputc(ch, outFile);
ch = fgetc(inFile);
}
}
Nothing in your program should behave differently depending on the name of the input or output file.
But you don't check whether the fopen() calls succeeded.
I think what's happening is that the input file with the .txt extension simply doesn't exist. This causes fopen to fail, returning a null pointer, which you then assign to inFile. fgetc(inFile) then crashes.
Always check whether your calls succeeded or failed.
And as I mentioned in a comment, you need to assign the result of fgetc() to an int, not a char. It returns either a character value or the negative value EOF.
In addition you don't need two calls to fgetc, one before the loop and the other in the loop.
Suggested reading: section 12 of the comp.lang.c FAQ.
I am getting segmentation fault when i compile my code.
I am not getting what is wrong with my code will be happy if someone can help me.
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
FILE *fp;
char fline[100];
char *newline;
int i,count=0,occ=0;
fp=fopen(argv[1],"r");
while(fgets(fline,100,fp)!=NULL)
{
count++;
if(newline=strchr(fline,'\n'))
*newline='\0';
if(strstr(fline,argv[2])!=NULL)
{
printf("%s %d %s",argv[1],count,fline);
occ++;
}
}
printf("\n Occurence= %d",occ);
return 1;
}
See man open and man fopen:
FILE *fp;
...
fp=open(argv[1],"r");
open returns an integer, not a file pointer. Just change that line to
fp=fopen(argv[1],"r");
Note: OP edited this error out of the code in the question, for those who wonder what this is about
Which leads us to (some other minor issues addressed as well - see comments):
+EDIT: point to places where error checking should be done:
#include<stdio.h>
#include<string.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *fp;
char fline[100];
char *newline;
int i, count = 0, occ = 0;
// for starters, ensure that enough arguments were passed:
if (argc < 3) {
printf("Not enough command line parameters given!\n");
return 3;
}
fp = fopen(argv[1], "r");
// fopen will return if something goes wrong. In that case errno will
// contain the error code describing the problem (could be used with
// strerror to produce a user friendly error message
if (fp == NULL) {
printf("File could not be opened, found or whatever, errno is %d\n",errno);
return 3;
}
while (fgets(fline, 100, fp) != NULL) {
count++;
if (newline = strchr(fline, '\n'))
*newline = '\0';
if (strstr(fline, argv[2]) != NULL) {
// you probably want each found line on a separate line,
// so I added \n
printf("%s %d %s\n", argv[1], count, fline);
occ++;
}
}
// it's good practice to end your last print in \n
// that way at least your command prompt stars in the left column
printf("\n Occurence= %d", occ);
return 1;
}
ps: so the error occurs during runtime and not during compile time - this distinction is quite crucial, because hunting down a compiler failure and solving a library usage error require rather different techniques...
I have reduced the program with comments, down to this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE * in;
in = fopen(argv[1], "r");
fclose(in);
fprintf(stderr, "clear **** \n");
return(0);
}
yet it still segfaults. Output is:
clear
Segmentation Fault
I know it's fclose(in) that's causing the problem, I just don't know why. For whatever reason, fclose(out) works perfectly fine.
First thing you should do is something like:
in = fopen(argv[1], "r");
if (in == NULL)
printf ("Could not open file '%s'\n" argv[1]);
else
fclose(in);
There's no guarantee in your original code that the fopen is actually working, in which case it will return NULL and the fclose will not be defined behaviour.