c++ - 如何使该函数与 FILE 一起使用? C++

标签 c++ c

我正在尝试编写两个传递FILE*的函数,这些函数创建另一个FILE*,其中它们将原始数据以小写和大写形式放入分别没有空格。

我想我明白了,但我不知道如何将 FILE* 传递给函数。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;

void minusculas (FILE *urFile);
void mayusculas (FILE *urFile);

main(){
    char s[256];
    FILE *pf;
    cout << "Tell me the name of the FIlE: ";
    gets(s);
    pf=fopen(s,"r");
}

void minusculas (FILE *urFile){
    char c; FILE *pf;
    urFile=fopen(urFile,"r");
    pf=fopen ("alliva.txt","w+");
    while (c!=EOF){
        c=getc(pf);
        if (c!=EOF)
            c=tolower(c);
        fprintf(pf,"%c" ,c);
    }
}

void mayusculas (FILE *urFile){
    char c; FILE *pf;
    urFile=fopen(urFile,"r");
    pf=fopen ("alliva.txt","w+");
    while (c!=EOF){
        c=getc(pf);
        if (c!=EOF && isspace(c)==0)
            c=toupper(c);
        fprintf(pf,"%c" ,c);
    }
}

我在函数中遇到错误。如何让程序变得更好?

最佳答案

pf=fopen(s,"r");

在此pf代表FILE *或打开文件的句柄。您可以直接在函数中传递它。检查 fopen 的手册页

您可以直接对文件句柄执行诸如 fgetcgetc 之类的操作。

除此之外,您的代码需要通过在不同位置适本地调用 fclose 来处理文件的关闭。

<小时/>

为了向您提供如何执行此操作的示例,请参阅以下函数:

void minusculas (FILE *urFile){
    char c; FILE *pf;
    //urFile=fopen(urFile,"r"); This is not needed
    pf=fopen ("alliva.txt","w+");
    while (c!=EOF){
        c=getc(urFile); //If you want to read from urFile
        if (c!=EOF)
            c=tolower(c);
        fprintf(pf,"%c" ,c);
    }
    fclose(pf)
}

您可以从 main 中调用此函数,如下所示:

pf=fopen(s,"r");
minusculas(pf)
fclose(pf)

关于c++ - 如何使该函数与 FILE 一起使用? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54287569/

相关文章:

c++ - 不同位数平台上 int_fastN_t 的正确位数是多少?

c++ - 在 Arduino 中同时执行多项功能

C unicode 到 ascii

c - 如何使用 cairo 绘制左上角和右下角的矩形?

c - Snprintf 在 C 中不工作

c - 使用 C 在客户端服务器上 read() write() 整数值

c++ - 在 C 中迭代 C++ 容器

c++ - 自动检测基类的类型参数

c++ - 模板函数,如何发送不同的结构并根据类型创建 if/else 语句?

c - 我不明白为什么我不能在c中获得三个输入