Segmentation fault while reading file - c

My file looks like:
123456789
My code gives me segmentation fault:
#include <stdio.h>
int main(){
FILE *f;
char ch[5];
f = open("a.txt", "r");
fgets( ch, 4, f);
ch[4] = NULL;
printf("%s", ch); //Fixed
return 0;
}
I am an absolute beginner. What am I doing wrong. My aim is to read first 4 characters of the file using fgets.

You'll want to do
printf("%s", ch);
For the % format, the argument is a pointer to characters; by passing a single character by value, you're telling printf to interpret that character's ASCII value as a pointer, and that's going to blow up on you; i.e., if the character is a 1, which is ASCII 49, then it's going to look at byte 49 in memory for a string -- and looking down there is generally verboten.
But secondly, I see you're calling open() instead of fopen(). You must use fopen() or you won't get a FILE* as you're expecting.
Both of these individually would likely cause a segfault -- you'll need to fix them both.

try to use "fopen" instead just "open"
Thanks.

Couple of quick changes.
I think you want to use fopen rather than open here, since you used a file pointer.
You need to increase the bytes read to 5, the last one is terminated by a null by fgets.
int main() {
FILE *f;
char ch[5];
f = fopen("a.txt", "r");
fgets( ch, 5, f);
printf("%s", ch);
return 0;
}

try to use
#include <stdio.h>
int main(){
FILE *f;
char ch[5];
f = fopen("a.txt", "r"); //use fopen
fgets( ch, 4, f);
ch[4] = NULL;
printf("%s", ch); // modification here pass the address of an array to printf
return 0;
}
try following example from the refereed site
/* fgets example */
#include <stdio.h>
int main()
{
FILE * pFile;
char mystring [5];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
if ( fgets (mystring , 5 , pFile) != NULL )
puts (mystring);
fclose (pFile);
}
return 0;
}
refer http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
you can also use
fgetc() :Get character from stream (function)

Related

fscanf doesn't read the first char of first word (in c)

I'm using fscanf function in a c code to read a file contains 1 line of words separated by white spaces, but for example if the first word is 1234, then when I print it the output is 234, however the other words in the file are read correctly, any ideas?
FILE* file = fopen(path, "r");
char arr = getc(file);
char temp[20];
while(fscanf(file,"%s",temp)!= EOF && i<= column)
{
printf("word %d: %s\n",i, temp);
}
char arr = getc(file);
Probably above line is causing to loose the first char.
Here is the posted code, with my comments
When asking a question about a run time problem,
post code that cleanly compiles, and demonstrates the problem
FILE* file = fopen(path, "r");
// missing check of `file` to assure the fopen() was successful
char arr = getc(file);
// this consumed the first byte of the file, (answers your question)
char temp[20];
while(fscanf(file,"%s",temp)!= EOF && i<= column)
// missing length modifier. format should be: "%19s"
// 19 because fscanf() automatically appends a NUL byte to the input
// 19 because otherwise the input buffer could be overrun,
// resulting in undefined behaviour and possible seg fault event
// should be checking (also) for returned value == 1
// this will fail as soon as an `white space` is encountered
// as the following call to fscanf() will not read/consume the white space
// suggest a leading space in the format string to consume white space
{
printf("word %d: %s\n",i, temp);
// the variable 'i' is neither declared nor modified
// within the scope of the posted code
}
char arr = getc(file);
reads the first character from the file stream and iterates the file stream file
you can use rewind(file) after char arr = getc(file) to reset your file stream to the beginning.
Other example:
#include <stdio.h>
int main(void)
{
FILE *f;
FILE *r;
char str[100];
size_t buf;
memset(str, 0, sizeof(str));
r = fopen("in.txt", "r");
f = fopen("out.txt", "w+b");
fscanf(r, "%s", str);
rewind(r); // without this, the first char won't be written
buf = fread(str, sizeof(str), 1, r);
fwrite(str, sizeof(str), 1, f);
fclose(r);
fclose(f);
return (0);
}

C Programming Read file and store it as a string [duplicate]

This question already has answers here:
Reading the whole text file into a char array in C
(5 answers)
Closed 8 years ago.
I wrote c code which input value for my program comes from here :
char *input[] = {"This input string value !!!", NULL};
But how can I read this value from the file (e.g. input.txt)? Is it possible to get the file content like a string?
Thanks a lot!
If you want to read a file line-by-line, the easiest way to go is using getline. Read the man page for a detailed description and a good code example.
getline will do all the low-lvel plumbing work of allocating buffers, copying data and scanning for newline characters, etc for you. Keep in mind that this is only possible since getline uses dynamically allocated memory that you'll need to free again.
On recent Posix compliant systems you could use getline(3), something like
FILE *fil = fopen("somefile.txt", "r");
if (!fil) {perror("somefile.txt"); exit(EXIT_FAILURE); };
char*linbuf = NULL;
size_t siz = 0;
ssize_t linlen = 0;
while ((linlen=getline(&linbuf, &siz, fil))>0) {
// linbuf contains the current line
// linlen is the length of the current line
do_something_with(linbuf, linlen);
};
fclose(fil);
free(linbuf), linbuf=NULL;
linlen = 0, siz = 0;
You can use fgets() like this:
#include <stdio.h>
int main(void)
{
char buffer[100];
FILE *file = fopen("input.txt", "r");
// Checks if the file was opened successfully
if (file == NULL)
{
fputs("Failed to open the file\n", stderr);
return -1;
}
// fgets here reads an entire line or 99 characters (+1 for \0) at a time, whichever comes first
while (fgets(buffer, sizeof(buffer), file) != NULL)
{
printf("Line read = %s\n", buffer);
}
fclose(file);
}
You can also use fgetc() like this:
#include <stdio.h>
int main(void)
{
int ch;
FILE *file = fopen("input.txt", "r");
// Checks if the file was opened successfully
if (file == NULL)
{
fputs("Failed to open the file\n", stderr);
return -1;
}
// fgetc reads each character one by one until the end of the file
while ((ch = fgetc(file)) != EOF)
{
printf("Character read = %c\n", ch);
}
fclose(file);
}

Read a file then store numbers in array C

so I have this file called "score.txt" with contents
NAME
20
NAME2
2
And I'm using this code but it gets an error and I have no idea on how to put the integers from the file in an array.
int main(){
FILE* file = fopen ("score.txt", "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
system("pause");
}
I'm only self learning and i've been trying to figure this out for 2hours already
The problem with using fscanf for input where some lines will fail the format is that the file will not be advanced per iteration of the while loop, so you get stuck.
You can get a solution by using fgets to grab the data and sscanf to grab the number:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void) {
int i = 0;
int ret = 0;
char buf[50];
FILE *file = fopen("score.txt", "r");
if (file == NULL) {
fprintf(stderr,"Unable to open file\n");
exit(1);
}
while (fgets(buf,sizeof(buf),file)) {
ret = sscanf(buf,"%d",&i);
if (ret == 1) { // we expect only one match
printf("%d\n", i);
} else if (errno != 0) {
perror("sscanf:");
break;
}
}
fclose(file)
return(0);
}
This will output, for your input:
20
2
We check the output of sscanf as it tells us if the format has been matched correctly, which will only happen on the lines with integer, and not the 'NAME' lines. We also check for 'errno' which will be set to non-zero if sscanf encounters an error.
We used char buf[50]; to declare a char array with 50 slots, which fgets then uses to store the line its reading; however if the line is more than 50 chars in length it will be read in 50 char chunks by fgets, and you may not get the results you desire.
If you wish to store the integers you read into an array, you'll have to declare an array, then on each read assign a slot in that array to the value of the int you read i.e. int_array[j] = i (where j will have to change with each slot you use). I'll leave it as an exercise to implement this.

How do I Extract a part of a line from a file?

I'm really new to C, so sorry if this is a dumb question but let's say I have a file containing the following:
1 abc
2 def
3 ghi
If I pass in an integer like 3 (Or character?) the function will return a string of "ghi". I don't know how to make this happen.
void testFunc(int num)
{
FILE *fp;
fp = fopen("testfile.txt", "r");
if(strstr??????
}
Yea.. I have no idea what I'm doing. Can anybody offer any guidance?
You can follow this link, you can do a bit google also.
Its really simple you should try your own once.
Reading c file line by line using fgetc()
Use fgets to read each line
Use sscanf to save the first and second elements of each line to variables
Test whether the number = 3, and if so print the word.
The man pages should give you all the info you need to use fgets and sscanf
Try this code
void testFunc(int num)
{
FILE *file = fopen ( "testfile.txt", "r" );
char line [ 128 ]; /* or other suitable maximum line size */
if ( file != NULL )
{
while ( fgets ( line, sizeof(line), file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
}
//input:num, output:string, string is call side cstring area.
void testFunc(int num, char *string){
FILE *fp;
int n;
fp = fopen("data.txt", "r");
while(2==fscanf(fp, "%d %s ", &n, string)){
if(num == n){
printf("%s\n",string);
break;
}
}
fclose(fp);
return;
}

fgets to read particular size

I'm trying to write a program that reads a certain amount of characters from a file name given from command line. Here is what I have:
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
FILE *f;
char* fileName = argv[1];
char buf[40];
f = fopen(fileName, "r");
while(!feof(f)){
fgets(buf, 10, f);
printf("%s\n", buf);
}
fclose(f);
return 1;
}
Say in this particular case I need first 10 chars, then the next 10 chars, etc until the file is over. However, when I run this code it doesn't actually give me the right output. I tried 11 as well since the documentation said fgets() reads n-1 characters, but that doesn't work either. Some stuff at the beginning is read, but nothing afterwards is and it just gives me a bunch of blanks. Any idea what is wrong?
Thanks
The function you are looking for is fread, like this:
fread(buf, 10, 1, f);
It works almost ok if you remove the \n from your printf format string (assuming that you want to basically echo a whole file as is).
I would also loop based on fgets(...) != NULL since feof() will return a true value after fgets errors and hits EOF, so your last buffer-full will be printed twice. You could make a small change to your code as so:
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
FILE *f;
char* fileName = argv[1];
char buf[40];
f = fopen(fileName, "r");
while(fgets(buf, 10, f))
printf("%s", buf);
fclose(f);
return 0;
}
Also, as others have stated, while I took too long to answer, fread may be a better alternative since fgets won't necessarily read 10 chars; it'll stop at every newline and you don't care about reading a line at a time.
fgets is intended to read a line, up to a maximum length. If you want to read 10 characters at a time, regardless of line breaks, you probably want to use fread instead:
Either way, you definitely do not want to use while (!feof(f)). You probably want something like:
int main(int argc, char **argv) {
char buf[40];
FILE *f;
if (NULL == (f=fopen(argv[1], "r"))) {
fprintf(stderr, "Unable to open file\n");
return EXIT_FAILURE;
}
size_t len;
while (0 < (len=fread(buf, 10, 1, f)))
printf("%*.*s\n", len, len, buf);
return 0;
}

Resources