C - Schreibe die Ausgabe in eine Datei

EDIT: 

void print(const int *v, const int size) {
 FILE *fpIn;
 fpIn = fopen("char-array.txt", "a");
 int i;  
 if (v != 0) {
   for (i = 0; i < size; i++) {
     printf("%d", (int)v[i]);
     fprintf(fpIn, "%d\n", (int)v[i]);   
   }
   perm_count++;
   printf("\n");
 }
 fclose(fpIn);
} 

Ich denke, das ist eine relativ einfache Frage 🙂

Grundsätzlich ist das Programm eine permutation Algorithmus, und drucken Sie die Ausgabe auf der standard-Ausgabe in der Konsole. Ich will auch zu schreiben, den Inhalt einer Datei via fprintf, nehme ich an. Obwohl ich kann nicht scheinen, um es arbeiten. Nur es druckt sinnlose Zeichen in die erste Zeile der text-Datei und mehr nicht !

Ich werde fügen Sie den folgenden code, und Hilfe ist sehr willkommen ! Das schreiben, um den Datei-code befindet sich innerhalb der print-Funktion.

Dank,

T.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>

#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf("%2.3f seconds used by the processor.", ((double)stopm-          startm)/CLOCKS_PER_SEC);

int perm_count = 0; 

void print(const int *v, const int size) {
  FILE *fpIn;
  fpIn = fopen("char-array.txt", "wb");
  int i;  
  if (v != 0) {
    for (i = 0; i < size; i++) {
      printf("%d", (char)v[i]);
      fprintf(fpIn, "%d", v[i]);  
      fprintf(fpIn, "\n");  
    }
    perm_count++;
    printf("\n");
  }
} 


void permute(int *v, const int start, const int n) {  
  int i;  
  if (start == n-1) {
    print(v, n);
  }
  else {
    for (i = start; i < n; i++) {
      int tmp = v[i];
      v[i] = v[start];
      v[start] = tmp;
      permute(v, start+1, n);
      v[start] = v[i];
      v[i] = tmp;
    }
  }
}

int main() {
 int i, x;
 printf("Please enter the number of terms: ");
 scanf("%d", &x);
 int arr[x];   
 printf("Please enter the terms: ");
 for(i = 0; i < x; i++)
 scanf("%d", &arr[i]);
 START
 permute(arr, 0, sizeof(arr)/sizeof(int));
 STOP   
 printf("Permutation Count: %d\n", perm_count);
 PRINTTIME
 return 0;
}
  • Ich würde gerne vorschlagen, weniger Abhängigkeit von Makros für Aufgaben, die leicht gehandhabt werden können über Funktionen statt.
  • +1 @sarnold. Ihre zukünftige Debuggen selbst wird es Ihnen danken.
InformationsquelleAutor PnP | 2012-02-10
Schreibe einen Kommentar