PROBLEM OPENING FILE WITH FILE*

Write your question here.
What I am doing wrong with these statement?

FILE* pfile;
pfile = fopen_s ("students.csv", "w");


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
 #include <stdio.h>
#include <cstdlib>
#include <string>
#include <iostream>

using namespace std;

#include "structs.h"

#define STUDENTS 3

int main(void)
{
	student students[STUDENTS];

	// populate students with user input
	for (int i = 0; i < STUDENTS; i++)
	{
		printf_s("Student's name: ");
		cin >> students[i].name;

		printf_s("Student's house: ");
		cin >> students[i].house;
	}

	// save students to disk
	FILE* pfile;
	pfile = fopen_s ("students.csv", "w");

	if (pfile != NULL)
	{
		for (int i = 0; i < STUDENTS; i++)
		{
			fprintf_s(pfile, "%s,%s\n", students[i].name, students[i].house);
		}
		fclose(pfile);
	}
	
}


header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
*	structs.h
*	Defines a student
*
*/

#include <string>
using namespace std;

// structure representing a student
typedef struct
{
	string name;
	string house;
}
student;

The short answer is use fopen instead of fopen_s.
( Or much better, use C++'s <fstream> )

Based on fopen_s's doc, it's form is :
errno_t fopen_s( FILE** pFile, const char *filename, const char *mode );

Therefore that statement should be :
1
2
3
4
FILE* pFile;
if( fopen_s( &pFile, "students.csv", "w" ) == 0 ) {
    // ...
}


http://msdn.microsoft.com/en-us/library/z5hh6ee9.aspx

Note that printf wants a cstring and not std::string. You must use std::string's method, c_str() w/c returns it's c-string equivalent.
fprintf_s( pfile, "%s,%s\n", students[i].name.c_str(), students[i].house.c_str() );

You also won't need typedef in the struct definition, you can write struct student { }; instead.

Here's a version of ur code using <fstream>
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
#include <iostream>
#include <fstream>
#include "structs.h"

using namespace std;

int main(void)
{
    const int STUDENTS = 3;          // or constexpr in C++11
    student students[STUDENTS]; // you can also use std::vector<student> for a resizable array

    // populate students with user input
    for (int i = 0; i < STUDENTS; i++)
    {
        cout << "Student's name: ";
        cin >> students[i].name;

        cout << "Student's house: ";
        cin >> students[i].house;
    }

    // save students to disk
    ofstream file( "students.csv" );

    for (int i = 0; i < STUDENTS; i++)
    {
        file << students[i].name << ',' students[i].house << '\n';
    }
}
Last edited on
nvrmnd,

An absolutely fantastic answer. I have learned so much. I now know the difference between a c-string and a c++-string and how important it is to know and understand the syntax.

Thank you very much.
Topic archived. No new replies allowed.