C – 将输出写入文件

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); } 

我想这是一个相对简单的问题:)

基本上该程序使用置换算法,并将输出打印到控制台中的标准输出。 我还想通过fprintf将内容写入文件。 虽然我似乎无法让它工作。 它只是将垃圾字符打印到文本文件的第一行,仅此而已!

我将粘贴下面的代码,非常感谢帮助! 在print函数中可以找到写入文件代码。

谢谢,

T.

 #include  #include  #include  #include  #include  #include  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; } 

1. fopen调用中的访问模式不正确
您将文件打开为二进制文件fopen("char-array.txt", "wb"); 。 如果要在那里写格式化字符串,请不要将b放到包含访问模式的字符串中。 由于您可能希望在文件末尾附加新数据而不是覆盖它们,因此请使用a代替w

 fopen("char-array.txt", "a"); 

2.写入输出缓冲区,而不是直接写入文件
当您使用fprintf之类的函数时 ,不直接写入文件而是写入输出缓冲区。 您必须使用fflush将输出缓冲区中的数据写入文件,或者您可以使用fclose函数关闭文件,该函数会自动刷新此缓冲区。

只需添加以下行:

 fclose(fpIn); 

printfunction结束时。

3.输出格式不正确
你不应该将intchar 。 它会截断你的数字。 你也有fprintf(fpIn, "\n"); 我猜错了。 它可能看起来像这样:

 for (i = 0; i < size; i++) { printf("%d ", v[i]); fprintf(fpIn, "%d ", v[i]); } perm_count++; printf("\n"); fprintf(fpIn, "\n"); 

不要浪费你的时间做你不需要的编程,使用fprintf很好但是你想要做的就是打印输出,你可以直接使用UNIX内置命令将东西打印到文件中。 假设你的程序被称为wirteoutput那么你所要做的就是从shell writeoutput > file.txt调用它时传递以下命令。 你必须使用的只是printf函数。

如果您对此感到好奇,这是一个旧function,您可以在原始论文UNIX操作系统中找到详细说明。 请查看标准I / O部分。

当你像屏幕显示一样写入文件时,你没有转换为char (来自int )。 以下内容将在您在屏幕上看到的文件中提供相同的数字:

 fprintf(fpIn, "%d", (char)v[i]);