c++ - 无法在Linux上使用流打印文件

标签 c++ linux file stream

我试图从c编程代码中删除多行注释。我需要从文件中获取输入,然后需要获取输出。在Windows系统中效果很好。我认为问题出在Linux的文件路径中。请帮帮我。

#include <iostream>
#include<fstream>
#include<string.h>
#include<ctype.h>

using namespace std;

int main()
{
    ifstream readfile("read.txt");
    ofstream writefile ("write.txt");
    string oneline;
    int mark=0;

    if(readfile.is_open())
    {
        while(getline(readfile,oneline))
        {
            int length=oneline.length()+1;

            char* newoneline=new char[length];
            strcpy(newoneline,oneline.c_str());
            for(int i=0;i<length;i++)
            {
               if(newoneline[i]=='/'&& newoneline[i+1]=='/')
               {
                  break;
               }
               if(newoneline[i]=='/'&& newoneline[i+1]=='*')
               {
                   mark=1;
               }
               else if(newoneline[i]=='*'&& newoneline[i+1]=='/')
               {
                  mark=0;
                  break;
               }
               if(mark==0)
               {
                  writefile<<newoneline[i];
               }
           }
           writefile<<"\n";
        }
    }
    return 0;
}

最佳答案

我不知道为什么分配动态数组?您可以通过以下方式轻松使用类字符串查找操作:

ifstream readfile("read.txt");
ofstream writefile("write.txt");
string oneline;
int mark = 0;


if (readfile.is_open())
{
    while (getline(readfile, oneline))
    {
        for (std::size_t i{}, length{oneline.length()}; length > 1 && i != length - 1; i++)
        {
            if (oneline.at(i) == '/' && oneline.at(i + 1) == '/')
                break;
            else
            if (oneline.at(i) == '/' && oneline.at(i + 1) == '*')
                mark = 1;
            else 
            if (oneline.at(i) == '*' && oneline.at(i + 1) == '/')
            {
                mark = 0;
                break;
            }
            if (mark == 0)
                writefile << oneline.at(i);
        }
        writefile << std::endl;
    }
}


当然,这应该在您的循环中。


代码中也存在内存泄漏:您每次迭代都在创建动态数组而不释放它!
另外这行:if(newoneline[i]=='/'&& newoneline[i+1]=='/')导致未定义的行为(i +我将读取newOneLine [length]):您的循环条件应为i < lengith - 1

关于c++ - 无法在Linux上使用流打印文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60019806/

相关文章:

c - 使用内核模块锁定内部系统调用

c++ - Pthread 循环函数永远不会被调用

java - 以原子方式将 byte[] 写入文件

c++ - RenderTarget->GetSize 不工作

C++ "destructive procedural variant"导致先前版本的二叉搜索树丢失

linux - 如何将字符数组转换为整数

java - 从 java jar 文件加载文件

c - 使用缓冲区大小有限的 posix 读取

c++ - 给指针赋值抛出异常

c++ - Shared_ptr成员变量的多态分配