【问题标题】:Write to File With Recursion in C在 C 中使用递归写入文件
【发布时间】:2014-10-20 16:06:09
【问题描述】:

我有一个程序从文件中读取字符串,取出所有大写字母,然后将其存储在文件中。问题是,我不知道如何将它写入文件,除非每次调用函数时都创建一个新文件。

我想我真正要问的是,我怎样才能一遍又一遍地将文件传递给函数?我可以再次将指针参数传递给函数吗?

int main() {
FILE *inputFile;
inputFile = fopen("codedmessage.txt", "r");
char codedMessage[100];  // Will contain - HarjEtvyqaLbLdjlmO
char decodedMessage[100];
fgets(codedMessage, 100, inputFile);
FILE *outputFile;
outputFile = fopen("decodedmessage.txt", "r");
decode(codedMessage, strlen(codedMessage)-1, &decodedMessage);

return 0;
}

// Decodes the message and prints it to file
void decode(char msg[], int n, char dmsg[]) {
    if (!n) {
        if (isupper(msg[n])) {
            printf("%c", msg[n]);
            dmsg[n] += msg[n];
        }
    }
    else {
        decode(msg, n-1, *dmsg);
        if (isupper(msg[n])){
            printf("%c", msg[n]);
            dmsg[n] += msg[n];
        }
    }
}

编辑:操作系统通常是 Linux(特别是 Ubuntu 和 CentOS)

【问题讨论】:

  • 您认为无法FILE *传递给函数是否有特殊原因?
  • 在哪个操作系统上?

标签: c file pointers recursion parameters


【解决方案1】:

我相信使用 ofstream 更直接,所以我会这样做。基本上我所做的一切都是为了:

  • 将 outputFile 定义为 ofstream;
  • 将其传递给解码并通过

您可以改为将重定向标准输出更改为您的文件,然后简单地写入标准输出(您无需更改解码函数,它会按原样工作)。

尽管第二个过程很简单,但并不那么容易理解。如果你还想用:C modifying printf () to output to a file

否则,这里是一个示例:

#include <iostream>
#include <fstream>

void decode(char msg[], int n, char dmsg[], std::ofstream& out);

int main() {
    FILE *inputFile;
    inputFile = fopen("codedmessage.txt", "r");
    char codedMessage[100];  // Will contain - HarjEtvyqaLbLdjlmO
    char decodedMessage[100];
    fgets(codedMessage, 100, inputFile);
    std::ofstream outputFile;
    outputFile.open("decodedmessage.txt");
    decode(codedMessage, strlen(codedMessage) - 1, decodedMessage, outputFile);

    return 0;
}

// Decodes the message and prints it to file
void decode(char msg[], int n, char dmsg[], std::ofstream& out) {
if (!n) {
    if (isupper(msg[n])) {
        out << msg[n];    //This is what you want to print, is that correct?
        //printf("%c", msg[n]);
        dmsg[n] += msg[n];
    }
}
else {
    decode(msg, n - 1, dmsg, out);
    if (isupper(msg[n])){
        out << msg[n];
        //printf("%c", msg[n]);
        dmsg[n] += msg[n];
    }
}

}

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2020-03-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多