حذف بخشی از محتویات یک فایل در c++ - هفت خط کد انجمن پرسش و پاسخ برنامه نویسی

حذف بخشی از محتویات یک فایل در c++

+1 امتیاز
چجوری میشه بخشی از اطلاعاتی رو که در فایل txt نگهداری میکنم رو از فایل حذف کنم ؟

توضیح بیشتر : در یک تقویم یادداشت هایی رو که برای هر روز توی یک فایل متنی دخیره میکنم رو میخوام بتونم یکی یکی پاک کنم یعنی هر خطی که مورد نظرمه بتونم پاک کنم.
سوال شده آذر 21, 1392  بوسیله ی Elyas74 (امتیاز 1,144)   6 14 27
دوباره تگ گذاری شد بهمن 22, 1392 بوسیله ی BlueBlade

2 پاسخ

+4 امتیاز
 
بهترین پاسخ

راهش اینه که کل فایل رو بخونی بازنویسی کنی دوباره بریزی داخل فایل مثلا :

#include <iostream>
#include <fstream>
#include <vector>

void replaceLineFromFile(int index,std::string text,std::string location) throw (const char*)
{
    std::fstream file;
    // Reading whole file
    file.open(location,std::fstream::in);
    std::vector <std::string > contents;
    std::string temp;
    if(file.is_open())
    {
        while(std::getline(file,temp))
        {

            contents.push_back(temp);
        }

    }
    else
    {
        throw "Can not open file";
    }
    file.close();

    //Changing lines
    if(index<contents.size())
    {
        contents[index]=text;
    }
    else
    {
        throw "Wrong Index";
    }


     //Writing again to the file
    file.open(location,std::fstream::out);
    if(file.is_open())
    {
        for(std::string i : contents)
           file<<i<<"\n";
    }
    else
    {
        throw "Can not open file";
    }

    file.close();
}
int main()
{
    try
    {
         replaceLineFromFile(2,"Some new Text","D:\\a.txt");
    }
    catch(const char* exc)
    {
        std::cout<<exc;
    }
}

 

پاسخ داده شده آذر 21, 1392 بوسیله ی BlueBlade (امتیاز 15,315)   15 18 89
انتخاب شد آذر 21, 1392 بوسیله ی Elyas74
+3 امتیاز

بدین صورت هم می تونید لیستی از شماره خط ها رو بهش بدید براتون پاک کنه.

 

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

void delete_indexs_from_file(string file_name,vector<int> indexs){
	sort(indexs.begin(),indexs.end());
	fstream file_in(file_name,ios::in );
	stringstream out;
	int cur_index = 0;
	string cur_line;
	vector <string> list;
	int index_pos = 0;
	while (std::getline(file_in ,cur_line))
	{
		if (index_pos < indexs.size() && cur_index++ == indexs[index_pos])
		{
			index_pos++;
		}
		else out << cur_line << endl;

	}

    file_in.close();
	fstream file_out(file_name,ios::out);
	file_out << out.rdbuf();
	file_out.close();
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> delete_list;
	delete_list.push_back(2);
	delete_list.push_back(5);
	delete_indexs_from_file("c:\\test.txt",delete_list);

{

پاسخ داده شده آذر 21, 1392 بوسیله ی مصطفی ساتکی (امتیاز 21,998)   24 34 75
...