I am trying to solve the problem of recursion. The problem is : Given a number n, print out all the possible combinations of set {a, b, ..., a n-1}. Output the answer in "output-n.txt". 1<=n<=9.
Here's my code:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void comb(int n,int curlen,int j,int num[],int flag) {
int i,k;
char filename[20] = "output-0.txt";
filename[7] = n '0';
char ans[20] = { 0 };
FILE* fptr;
fptr = fopen(filename, "a");
if (fptr != NULL) {
if (curlen < n && flag != 0) {
for (i = 0; num[i] != 0; i ) {
ans[i] = num[i] '`';
}
for (k = 0; k <= curlen; k ) {
fprintf(fptr, "%c", ans[k]);
}
fprintf(fptr, " ");
if (curlen == 0 && num[0] == n) {
fclose(fptr);
}
else {
comb(n, curlen 1, j 1, num, 0);
}
}
else {
for (; j <= n; j ) {
num[curlen] = j;
comb(n, curlen, j, num, 1);
}
}
}
}
int main() {
int n,flag=0,num[20] = { 0 };
scanf("%d", &n);
comb(n, 0, 1, num, flag);
system("pause");
return 0;
}
My program is doing fine while 1<=n<=7, but at n=8 and n=9, the FILE pointer becomes NULL in the middle and can only output part of the answers. I looked closely to the output .txt file and realized that both of the files can only output to the 254th row.I wonder did I make any mistake. Thanks for answering.
CodePudding user response:
You have hit the limit for the number of open files.
You keep opening the same file for append and don't always close it. When I rearranged the code so that it opens the file once in main
in "w"
mode, it works correctly.
#include <stdio.h>
#include <stdlib.h>
void comb(FILE *fptr, int n,int curlen, int j, int num[], int flag) {
int i,k;
char ans[20] = { 0 };
if (curlen < n && flag != 0) {
for (i = 0; num[i] != 0; i ) {
ans[i] = num[i] '`';
}
for (k = 0; k <= curlen; k ) {
fprintf(fptr, "%c", ans[k]);
}
fprintf(fptr, " ");
if (curlen == 0 && num[0] == n) {
//fclose(fptr);
}
else {
comb(fptr, n, curlen 1, j 1, num, 0);
}
}
else {
for (; j <= n; j ) {
num[curlen] = j;
comb(fptr, n, curlen, j, num, 1);
}
}
}
int main() {
int n,flag=0,num[20] = { 0 };
char filename[20] = "output-0.txt";
if(scanf("%d", &n) != 1 || n < 1 || n > 9) // sanity check
return 1;
filename[7] = n '0';
FILE *fptr = fopen(filename, "w"); // open once
if(fptr != NULL) {
comb(fptr, n, 0, 1, num, flag); // pass the file pointer
fclose(fptr);
}
return 0;
}