C代写:CS50 C Programming request6

Note

  • Work on an request by yourself without sharing the answer to a classmate. (It is great that students study together but an request is an individual task. It is not a group project.)
  • Start to do an request early and ask the teacher if you have a question.
  • Add a comment with your name at the top of your source code
  • Put all your files that you want to submit into one zip file
  • Your folder should have your last name, first name, your class and request number. Example: rattanasook_hathairat_cs50_6.zip
Please save the program with the name ‘files.c’

Write a program that merges two files as follows. The two files are in the docsharing which you can download it.
One file will contain usernames (usernames.txt):

1
2
3
4
foster001
smith023
nyuyen002

The other file will contain passwords (passwords.txt):

1
2
3
4
x34rdf3e
p43e4rdd
w32eds22

The program should create a third file matching username and passwords (usernamesPasswords.txt):

1
2
3
4
foster001 x34rdf3e
smith023 p43e4rdd
nyuyen002 w32eds22
… …

Give the user of your programs the option of displaying you output file.

Tips

下边是完整实现

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

#define USERNAME_FILE "usernames.txt"
#define PASSWORD_FILE "passwords.txt"

#define COMBINE_FILE "usernamesPasswords.txt"

int main(int argc, char *argv[]){
int display; // Whether to show result
FILE* u_file; // File handler to username
FILE* p_file; // File handler to password
FILE* o_file; // File handler to output file
char line_u[128];
char line_p[128];
char line_o[512];

if(argc == 2 && strcmp(argv[1], "-s") == 0){
display = 1;
}else{
printf("You can add -s option to display output.\n");
display = 0;
}

// Open file
u_file = fopen(USERNAME_FILE, "r");
p_file = fopen(PASSWORD_FILE, "r");
o_file = fopen(COMBINE_FILE, "w");

// Read file line by line
while(!feof(u_file)){
fgets(line_u, 128, u_file);
fgets(line_p, 128, p_file);

// Replace '\n' to '\0'
line_u[strlen(line_u) - 1] = '\0';

// Concat strings
sprintf(line_o, "%s\t%s", line_u, line_p);
if(display == 1){
printf("%s", line_o);
}
// Output file
fprintf(o_file, "%s", line_o);
}

// Close file handler
fclose(u_file);
fclose(p_file);
fflush(o_file);
fclose(o_file);

printf("\n");
system("pause");
return 0;
}