C source - error
Heya guys i have codet C program that read from .txt file and display his content but convert all characters into their integer values ( some like C++ ATOI() function ascci to integer) but when i try to run it with GCC look what happens >>> Enter file name: fuking error Segmentation fault (core dumped)
can anyone help me out? theres the code :
#include <stdlib.h>
#include <string.h>
int main()
{
char name[256];
FILE *fp;
printf("Enter file name: \n");
fgets(name,256,stdin);
strcat(name, ".txt");
fp = fopen(name, "r");
int exml;
while ( (exml = fgetc(fp)) !=EOF)
{
printf("%d",exml);
}
fclose(fp);
return 0;
} ```
no its not the problem i tried a lot of combinations none works…. :xx: is it possible problem to be in my OS i am running Ubuntu…. maybe my Os wont let the program to access to files? there is one more changed version does not work too :@
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[256];
FILE *fp;
printf("Enter file name: \n");
scanf("%s",buffer);
strcat(buffer, ".txt");
fp = fopen(buffer, "r");
char c;
while (fscanf(fp,"%c",&c)!=-1)
{
printf("%c",c);
}
fclose(fp);
return 0;
}```
this should work
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[256];
FILE *fp;
printf("Enter file name: \n");
fgets(buffer,80,stdin);
int i;
i = strlen (buffer)-1;
if (buffer[i]=='\n') buffer[i]='\0';
if ((fp = fopen(buffer, "r"))==NULL)
{
printf ("cannot open a file %s %s",buffer,"\n");
exit(1);
}
int c;
while (fscanf(fp,"%c",&c)!=-1)
{
printf("%c",c);
}
fclose(fp);
return 0;
}
there are several methods to get it but first make sure that you have the file name in buffer second make sure the file is open
BLAST, you beat me to this but I will post this anyways, which also works.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char file_path[100];
char file[1000];
printf("Please enter your file you wish to read:\n");
scanf("%s", &file_path);
strcat(file_path, ".txt");
FILE *f;
f=fopen(file_path,"r");
while (fgets(file,1000,f)!=NULL)
printf("%s \n", file);
fclose(f);
return 0;
}