Good Day,
I have tried all day to get the program to work. I think there's some linking problem somewhere... Please kindly help. Tks in advance.
1) Names are to be initialised into names.dat by program1
. *names no longer than 20 char
. *names will have no spaces
2) Program2 will copy the names will <=5 characters in small.dat
. and those <5 into large.dat
3) Program3 will output all three *.dat onto screen
Program1
Code:
/*program to initialise data into names.dat*/
#include <stdio.h>
int main (void)
{
FILE *cfPtr;
char ch[21];
int choice;
if((cfPtr = fopen("names.dat", "w")) == NULL){
puts("The file names.dat cannot be opened.");
return 0;
}
else{
do{
puts("Enter 0 to insert name. Other digit to end.");
scanf("%d", &choice);
if(choice != 0){
fclose(cfPtr);
return 0;
}
puts("Please enter names.");
fflush(stdin);
gets(ch);
fputs(ch, cfPtr);
fputc('\n', cfPtr);
}while(choice == 0);
}
return 0;
}
Program2
Code:
/*program (which reads from names.dat) to copy names with <= 5 characters
into small.dat and those over 5 into large.dat*/
#include <stdio.h>
#include <string.h>
#define MAX_STR_LENGTH 255
main(void) {
char inputBuffer[MAX_STR_LENGTH], processed[20];
FILE *infp, *outfp1, *outfp2;
infp = fopen("names.dat", "r");
if (infp == NULL) {
puts("Error - names.dat");
exit(1);
}
outfp1 = fopen("small.dat", "w");
if (outfp1 == NULL) {
puts("Error - small.dat");
exit(1);
}
outfp2 = fopen("large.dat", "w");
if (outfp2 == NULL) {
puts("Error - large.dat");
exit(1);
}
while (fgets(inputBuffer, MAX_STR_LENGTH, infp) != NULL) {
sscanf(inputBuffer, "%s", processed);
if (strlen(processed) < 6) {
fputs(processed, outfp1);
fputc('\n', outfp1);
}
else{
fputs(processed, outfp2);
fputc('\n', outfp2);
}
}
return 0;
}
Program3
Code:
/*program to output the data of 3 files
1) names.dat
2) small.dat
3) large.dat
*/
#include <stdio.h>
int main (void)
{
FILE *namesFP, *smallFP, *largeFP;
char ch[21], input[21];
namesFP = fopen("names.dat", "r");
puts("The names in names.dat are:");
if (namesFP == NULL)
puts("names.dat cannot be opened.");
else
while(fgets(input, 21, namesFP) != NULL){
sscanf(input, "%s", ch);
puts(ch);
}
fclose(namesFP);
smallFP = fopen("small.dat", "r");
puts("");
puts("");
puts("The names in small.dat are:");
if (smallFP == NULL)
puts("small.dat cannot be opened.");
else
while(fgets(input, 21, smallFP) != NULL){
sscanf(input, "%s", ch);
puts(ch);
}
fclose(smallFP);
largeFP = fopen("large.dat", "r");
puts("");
puts("");
puts("The names in large.dat are:");
if (largeFP == NULL)
puts("large.dat cannot be opened.");
else
while(fgets(input, 21, largeFP) != NULL){
sscanf(input, "%s", ch);
puts(ch);
}
fclose(largeFP);
return 0;
}