fscanf Seg fault

closed account (ybq5Djzh)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

struct studentinfo
{
	int roll;
	char name[30];
	int batch;
	float marks;
};

void printstudent (struct studentinfo s)
{
	printf ("%5d %30s %3d %5.2f\n", s.roll, s.name, s.batch, s.marks);
}

int main ()
{
	struct studentinfo s;
	int rec_size;
	rec_size = sizeof (struct studentinfo);
	cout << "Size of record is: " << rec_size << endl;
	FILE *fp_input, *fp_output;
	fp_input = fopen ("markdata.txt", "r+");
	if (fp_input = NULL)
	{
		cout << "Cannot open input file\n";
		return -1;
	}
	fp_output = fopen ("out.txt", "w+");
	if (fp_output = NULL)
	{
		cout << "Cannot open output file\n";
		return -1;
	}
	int r, b;
	char n[30];
	float m;
	int count = 0;
	fscanf (fp_input, "%d %s %d %f", &r, n, &b, &m);
	cout << endl;
	while (!feof (fp_input))
	{
		count++;
		s.roll = r;
		s.batch = b;
		strcpy (s.name, n);
		s.marks = m;
		cout << count << ": ";
		printstudent (s);
		fwrite (&s, rec_size, 1, fp_output);
		fscanf (fp_input, "%d %s %d %f", &r, n, &b, &m);
	}
	cout << "Tasks performed\n";
	fclose (fp_input);
	fclose (fp_output);
	return 0;
}


I'm getting a seg fault in line 42 in int main() for fscanf. Can you please tell me what's wrong? Thanks!
Last edited on
you have written

fscanf (fp_input, "%d %s %d %f", &r, n, &b, &m); // missing &

and the correct one is

fscanf (fp_input, "%d %s %d %f", &r, &n, &b, &m);
closed account (ybq5Djzh)
I am still getting a seg fault. Also it gives a couple of compile time warnings which says "format %s expects argument of type 'char*' but argument 4 has type 'char*[30]' [-Wformat]

Also, why do we need to put &n? It is already an array right?

Please help! I'm at my wits end!!
Also, why do we need to put &n? It is already an array right?
Yes, that's not the problem. Maybe the problem is that the string must not exceed 29 characters. To ensure this you should add the size to %s:

fscanf (fp_input, "%d %29s %d %f", &r, &n, &b, &m);
Topic archived. No new replies allowed.