C - 将输出写入文件

标签 c io fopen printf fclose

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 将内容写入文件。虽然我似乎无法让它工作。它只是将垃圾字符打印到文本文件的第一行,仅此而已!

我将粘贴下面的代码,非常感谢您的帮助!写入文件代码位于打印函数中。

谢谢,

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

最佳答案

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

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

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

只需添加这一行:

fclose(fpIn);

print 函数的末尾。

<强>3。输出格式不正确
您不应将 int 转换为 char。它会截断你的数字。我猜你还有 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");

关于C - 将输出写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9236201/

相关文章:

python - 如果在打开的同一行读取文件是否会自动关闭?

c - 我的错误是什么?

c - 在 C 中作为用户输入的文件路径

c - 如何为 C 结构体中的 char 指针分配内存?

c - C语言中全局变量和局部变量都存储在内存中

java - 从 FTP 服务器读取单行,无需使用 it.sauronsoftware.ftp4j.FTPClient 下载整个文件

c - 用 C 写入文件?

用于日期时间格式验证的 C 代码。指定格式为 "YYYYMMDDHHMMSSmmmmmm"

c - atomicAdd 导致错误无法启动/执行内核

c - 处理文本文件二