2010-03-07 82 views
0

如果我有我想要输出到一个文本文件中的整数数组..Ç - 输出到文件

void output() 
{ 
    for (i=0; i<10; i++) 
     printf("%d ", values[i]); 
} 

我如何保存()的输出使用下面的方法为文本文件?

void writeToFile() 
{ 
    file = fopen("file.txt","a+"); // apend file or create a file if it does not exist 
    fprintf(file,"%d", *missing parameter*); // write 
    fclose(file); // close file 
    printf("File created. Located in the project folder.\n", ""); 
} 
+0

它是关于如何组合两个函数来遍历数组值? – stacker 2010-03-07 09:59:59

+0

不要在人们费力回答之后删除你的问题。 – 2010-03-07 14:34:36

回答

0

只需创建两个函数:

void output() 
{ 
    for (i=0; i<10; i++) 
     printf("%d ", values[i]); 
} 

void output(FILE* file) 
{ 
    for (i=0; i<10; i++) 
     fprintf(file, "%d ", values[i]); 
} 
+0

+1为%d后的空白 – stacker 2010-03-07 10:05:52

+0

C不支持超载;-) – 2010-03-07 10:28:17

+0

-1。 C不支持重载。 第二个函数就够了:“void output(FILE * file);” 如果你想打印到标准输出,你可以使用第二个函数,如下所示:output(stdout); – 2010-03-07 10:39:04

4

作为一种替代方法来创建两个函数(按照AareP's answer),你可以一个目标参数添加到output()功能:

void foutput(FILE *dest, int values[]) 
{ 
    int i; 

    for (i=0; i<10; i++) 
     fprintf(dest, "%d ", values[i]); 
} 

然后,您可以将原始output()重新实现为简单包装:

void output(int values[]) 
{ 
    foutput(stdout, values); 
} 

在这种情况下,这可能看起来不太有用,但我把它放在这里,因为当输出函数的逻辑更加复杂时,这个通用模式会很有用。一般来说,最好将它保存在一个地方,而不是将其复制到多个函数中(这意味着您只需要在一个地方修复错误)。

1

添加到别人告诉:

你必须始终fopen之后检查错误,这对错误返回NULL

FILE *file = fopen("file.txt","a+"); 
if(!file) { 
     fprintf(stderr,"error opening file...exiting\n"); 
     exit(1); 
} 
0

如果你想重复使用你的输出函数,你可以这样做。 使用a_output函数,您将能够在控制台或任何其他输出流中打印结果。

#include <assert.h> 
#include <stdio.h> 

void a_output(FILE *fs, int *array, unsigned int array_s); 

void a_output(FILE *fs, int *array, unsigned int array_s){ 
    int i; 

    assert(fs != NULL); 
    assert(array != NULL); 

    for(i = 0; i < array_s ; i++){ 
     fprintf(fs, "%d ", array[i]); 
    } 
} 

int main(int argc, char **argv) 
{ 
    int array[5] = {1, 2, 3, 4, 5 }; 
    FILE *out; 

    if((out = fopen("output.txt", "w")) == NULL){ 
     return -1; 
    } 
    /* Will "print" results in a file */ 
    a_output(out, array, 5); 

    /* Will "print" results in console */ 
    a_output(stdout, array, 5); 

    fclose(out); 
    return 0; 
}