Originally Posted by
aengland643
I am fairly new to C as well so forgive my naivety
The simple fact that you're not new to English is a relief.
Your main problem is that you are trying to read an integer using a function that reads strings. (You should have got a warning about that.) To read a number as a number, use scanf:
The problem with scanf is that it leaves the newline in the input buffer, which can be a problem. You can eat the newline like so:
Code:
int ch;
while ((ch = getchar()) != EOF && ch != '\n') ;
25 spaces is a very small space for a file name. There's no reason not to make it 250 or more.
gets is a deprecated function due to it's security issues. fgets should be used instead, but it stores the newline character at the end of the string (if there's room). A simplistic way to get rid of the newline if it's there is:
Code:
fgets(filemerge, sizeof filemerge, stdin);
filemerge[strcspn(filemerge, "\n")] = '\0'; // include string.h for strcspn
You need to check that the files actually opened by testing whether the file pointer returned by fopen is not NULL.
fgetc returns an int, not a char, so ch should be an int. That way the value of EOF can be different from any possible char value (since an int is larger than a char).
There's no reason to leave all the input files open until the end. Instead, close each of them as soon as you're done with them. That means that you don't need an array of file pointers for the input files, but just one.
You don't need a separate strcat to add ".txt". You can do that in the sprintf.
Code:
sprintf(file, "%d.txt", i);
A 6 space tab is strange. 8 is old-fashioned. 4 is normal. People are even using 2 these days.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXFILENAME 250
int main() {
int nfiles;
printf("Enter the number of files to merge: ");
scanf("%d", &nfiles);
int ch;
while ((ch = getchar()) != EOF && ch != '\n') ; // eat the newline
char file_out[MAXFILENAME];
printf("Enter the name of the output file: ");
fgets(file_out, MAXFILENAME, stdin);
file_out[strcspn(file_out, "\n")] = '\0';
FILE *fout = fopen(file_out, "w");
if (!fout) {
perror("fopen output file");
exit(EXIT_FAILURE);
}
for (int i = 0; i < nfiles; i++) {
char file_in[MAXFILENAME];
sprintf(file_in, "%d.txt", i);
FILE *fin = fopen(file_in, "r");
if (!fin) {
perror("fopen input file");
fprintf(stderr, "Problem file: %s\n", file_in);
exit(EXIT_FAILURE);
}
while ((ch = fgetc(fin)) != EOF)
fputc(ch, fout);
fclose(fin);
}
fclose(fout);
return 0;
}