1

我有我的函数 dumpArray(); 这样做:

void dumpArray(void)
{
       while(p <= i)
       {
           printf("%i:", packet[p].source);
           printf("%i:", packet[p].dest);
           printf("%i:", packet[p].type);
           printf("%i\n", packet[p].port);
           p++;
       }
}

我正在尝试将其传递给 fprintf(); 像这样:

void fWrite(void)
{
    char fileName[30] = { '\0' };
    printf("Please specify a filename: ");
    scanf("%s", fileName) ;
    FILE *txtFile;
    txtFile = fopen(fileName, "w");
    if (txtFile == NULL)
    {
        printf("Can't open file!");
        exit(1);
    }
    else fprintf(txtFile, dumpArray());
}

我正在尝试编写 dumpArray(); 的结果 到文件中。
谁能看到我哪里出错并指出我正确的方向。

4

4 回答 4

3

You could rewrite dumparray to either write to stdout or to your textfile depending which stream you pass in.

So you would change all of your printf calls to fprintf and pass the stream as the first argument.

于 2012-05-03T23:13:16.310 回答
2

Your first function is dumping its output into stdout and returning nothing, so it just won't result in an output that fprintf can capture.

You'll need to figure out how long all of those printf strings are and allocate the appropriate amount of memory to sprintf it and then return the string.

Alternatively, you should pass a function pointer to dumpArray pointing at the printf-like function that will instead write to a file:

void printfLike(format, data) {
    fprintf(fileConst, format, data);
}

...

dumpArray(printfLike);

Something of that nature.

于 2012-05-03T23:14:32.983 回答
1

fprintf 的函数声明声明它需要一些 char* 参数,但 dumpArray() 没有返回 char*。

int fprintf ( FILE * 流, const char * 格式, ... );

如果要在 dumpArray() 中写入文件,可以将 txtFile 传递给 dumpArray() 并在函数内执行 fprintf。或者,您可以先将要写入文件的所有数据收集到缓冲区(例如 char[])中,然后将其全部写入。

例如:

void dumpArray(FILE * txtFile)
{
       while(p <= i)
       {
           fprintf(txtFile, packet[p].source);
           fprintf(txtFile, packet[p].dest);
           fprintf(txtFile, packet[p].type);
           fprintf(txtFile, packet[p].port);
           fprintf(txtFile, "\n");
         p++;
       }
}

void fWrite(void)
{
    char fileName[30] = { '\0' };
    printf("Please specify a filename: ");
    scanf("%s", fileName) ;
    FILE *txtFile;
    txtFile = fopen(fileName, "w");
    if (txtFile == NULL)
    {
        printf("Can't open file!");
        exit(1);
    }
    else dumpArray(txtFile);
于 2012-05-03T23:10:21.117 回答
0

Where do you start?

Plead look up the page for fprintf and printf.

Change dumpArray into reuturning a character array. WHat is p?

That is for starters - Re-read you text book on C and also manual pages on C

于 2012-05-03T23:12:59.030 回答