Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

cross platform - Adding text and lines to the beginning of a file (C++)

I'd like to be able to add lines to the beginning of a file.

This program I am writing will take information from a user, and prep it to write to a file. That file, then, will be a diff that was already generated, and what is being added to the beginning is descriptors and tags that make it compatible with Debian's DEP3 Patch tagging system.

This needs to be cross-platform, so it needs to work in GNU C++ (Linux) and Microsoft C++ (and whatever Mac comes with)

(Related Threads elsewhere: http://ubuntuforums.org/showthread.php?t=2006605)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See trent.josephsen's answer:

You can't insert data at the start of a file on disk. You need to read the entire file into memory, insert data at the beginning, and write the entire thing back to disk. (This isn't the only way, but given the file isn't too large, it's probably the best.)

You can achieve such by using std::ifstream for the input file and std::ofstream for the output file. Afterwards you can use std::remove and std::rename to replace your old file:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>

int main(){
    std::ofstream outputFile("outputFileName");
    std::ifstream inputFile("inputFileName");

    outputFile << "Write your lines...
";
    outputFile << "just as you would do to std::cout ...
";

    outputFile << inputFile.rdbuf();

    inputFile.close();
    outputFile.close();

    std::remove("inputFileName");
    std::rename("outputFileName","inputFileName");
    
    return 0;
}

Another approach which doesn't use remove or rename uses a std::stringstream:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

int main(){
    const std::string fileName = "outputFileName";
    std::fstream processedFile(fileName.c_str());
    std::stringstream fileData;

    fileData << "First line
";
    fileData << "second line
";

    fileData << processedFile.rdbuf();
    processedFile.close();

    processedFile.open(fileName.c_str(), std::fstream::out | std::fstream::trunc); 
    processedFile << fileData.rdbuf();

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...