C++ 文件访问/输入和输出

标签 c++ file

我在使用这个程序时遇到了困难(请参阅下面的代码)。它应该:

  1. 创建一个包含 26 个组件的数组,用于计算字母表中 26 个字母的字母数和一个用于行数的变量。

  2. 创建一个包含文本的 ASCII(或文本)文件,并将用作我的程序的输入。

  3. 将该文件称为“textinput”,然后将输出存储在名为“textoutput”的文件中。

谁能告诉我我做错了什么?我不断收到“找不到文件”错误。

#include <iostream>
#include <cstdio>
#include <iomanip>
#include <cstdlib>
#include <fstream>

using namespace std;

int main()
{
int lineCount = 0;
int letterCount[26];

for(int i = 0; i < 26; i++)
    letterCount[i] = 0;

ifstream infile;
infile.open("textinput.txt", ios::in);

if(!infile)
{
    cerr<<"File does not exist."<<endl;
    exit(1);
}

ofstream outfile;
outfile.open("textoutput.txt", ios::out|ios::binary);

if(!outfile)
{
    cerr<<"File cannot be opened."<<endl;
    exit(1);
}
char data[100];
outfile<<data;

while(infile>>data)
{
    outfile<<data<<endl;
}

while(infile)
{
    char ch1 = infile.get();
    if(ch1 == '\n')
    {
        lineCount++;
        continue;
    }

    int asciiNum = (int)ch1;
    if(asciiNum > 96)
    {
        asciiNum = asciiNum - 97;
    }
    else
    {
        asciiNum = asciiNum - 65;
    }

    letterCount[asciiNum]++;
}
infile.close();
outfile.close();
system("PAUSE");
return 0;
}

最佳答案

有趣的是,“找不到文件”错误在您的程序中是不可能出现的。1 所以,我冒昧地建议您需要限定您的路径可执行!

比如说,你用类似的东西编译

gcc program1.cpp -o program1

要执行,你必须使用

./program1

因为 program1 不会工作。原因是有 99% 的把握,您当前的工作目录不在可执行文件的搜索路径中(您希望保持这种状态)。

除此之外,是的,请确保 textinput.txt 存在于同一目录中。


1(程序中没有这样的错误信息,你应该知道:你编的!)

关于C++ 文件访问/输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17632739/

相关文章:

python - 无法使用 python 获得将 .xml 文件保存到磁盘的权限

mysql - max_connections 选项不适用于 mysqld

python - 在 Python 中连接两个文本文件

c++ - 来自函数模板的显式模板特化不起作用

c++ - 我可以声明一个位表吗?

c++ - for循环中使用的位操作

c - C语言打印文件大小和时间

c - 为什么 "read"必须是在 "Kernel Mode"中运行的系统调用?

c++ - 在 C++ 预处理器中拆分参数

c++ - LNK2005、LNK1169 错误, "int __cdecl g(void)"(?g@@YAHXZ) 已定义