C++ and C Similarities and Differences

Hello Everyone,

I want to teach myself some C. I was told it was not so necessary if I am already learning C++, but why not. I am trying to change the following C++ code to C, but I have a feeling it's completely wrong.

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

#include <cstring>
#include <fstring>
#include <iostream>

using namespace std;

int main( int argc, char** argv)
{
	// Sanity checking
	if (argc != 3) {
		cerr << "Usage: cp file1 file2\n";
		return 1;
	}

	if (strcmp (argv[1], argv[2], strlen (argv[1])) == 0) {
		cerr << argv[1] << "and" << argv[2]
		     << " are the same file\n";
		return 2;
	}

	ifstream ifs (argv[1]);
	if (!ifs) {
		cerr << "Cannot open " << argv[2] << " for reading\n";
		return 3;
	}

	ofstream ofs (argv[2]);
	if (!ofs) {
		cerr << "Cannot open " << argv[2] << " for writing\n";
		return 4;
	}

	char ch;
	while (ifs.get(ch))
		ofs << ch;

	// clean up
	ifs.close();
	ofs.close();
}


My Version:

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

#include<studio.h>
#include<cstring.h>
#include<string.h>
#include<stdlib.h>

int main (int argc,char ** argv)
{
	/*Sanity Checking*/
	if(argc!=3) {
		fprintf(stderr,"Usage:cp file1 file2\n");
		return 1;
	}

	int str1 = argv[1];
	int str2 = argv[2];
	int str_buffer = strlen (argv[1]):

	if(strcmp(str1, str2, str_buffer) == 0) {
		fprinf(stderr, str1, "and", str2, "are the same file\n");
		return 2;
	}

	File * ifp,* ofp;
	ifp = fopen("argv[1]", "r");

	if(!ifp) {
		fprinf(stderr, "Cannot open", argv[1], "for reading\n");
		return 3;
	}

	ofp = fopen("argv[2]", "w");

	if(!ofp) {
		fprintf(stderr, "Cannot open", argv[2], "for writing\n");
		return 4;
	}

	char ch [256];

	while (fgets (ch, 256, stdin) {
		fputs(ch, ifp);
		return 0;
	}

	/*Clean up */
	fclose(ipf);
	fclose(opf);


}


I read when using strcmp, you cannot compare pointers so I broke it up

1
2
3
4
5
6
7
8
9
10

	int str1 = argv[1];
	int str2 = argv[2];
	int str_buffer = strlen (argv[1]):

	if(strcmp(str1, str2, str_buffer) == 0) {
		fprinf(stderr, str1, "and", str2, "are the same file\n");
		return 2;
	}


And I struggled with the while loop. What I understood was that while loop reads input with ifs.get() and then writes it to the file.

1
2
3
4
5
6
7
8
9

	char ch [256];

	while (fgets (ch, 256, stdin)) {
		fputs(ch, ifp);
		return 0;
	}




Any advice would be greatly appreciated.
Thanks!
Last edited on
The way one programs in C completely contradicts the way one programs in C++. I highly recommend not learning them at the same time.
Do you think learning C would even be useful?
It would, but not at the same time as learning C++. Learn them at separate times.
Topic archived. No new replies allowed.