How to update a line from txt file depends on a condition? - struct

i have a problem in my code i tried many things but i could not solved.
The problem is i am codding a stock managment program(It is not about SQL or whatever comes to your mind), just a basic consol app for a school project.
My code is creating a product depends on a struct and then write on a file which one is called "database.txt".
Assume, a personel wants to change details of item according to its referance number(referance number defined like REF:)
When read the database file if the referance number founds i want to changes all line untill the next referance number. But when i try to change somethig went wrong like picture.
Before UpdatingAfter Updating
if(button2 == 2)
{
string refNo;
string word;
cout <<"Enter the referance number of item for update" << endl;
cin >> refNo;
refNo = "REF:"+refNo;
fstream file(databaseFile.c_str());
if(file.is_open())
{
while(getline(file, word))
{
if(word == refNo)
{
product entity = createItem(true);
file << entity.detail.category << endl;
file << entity.name << endl;
file << entity.price << endl;
file << entity.profitMargine << endl;
file << entity.stock << endl;
}
}
}
}

Completely Rewrite the entire file
Create a new file.
Copy the original file to the new file up to the start of your desire line you want to change (here the user's Ref:)
Write the new line in new file
Copy the remaining parts of original file to the new file
Close both original and new files. Delete the original file, and rename the new file

Related

Split flat file into multiple files

I need to create a package which splits the huge flat file into multiple flat files.
I have flat file which has 20 million rows and now I need to split this flat file (Each flat file needs to have 55 k rows)
Example:- if there are 111 rows in total, I would have to create 3 files.
file1.txt will have 1-55 rows
file2.txt will have 55-110 rows
file3.txt will have 1 rows
.
What options do I have?
I am using Visual Studio 2012 for this project.
you could try something like this... its pretty rudimentary and I am sure that someone will point out that it is not going to be the most efficient thing but its a solid option. Note that you will need to add some try catch error handling.
int recper = 0; // this is where you will assign the number of records per file
int reccount = 0;
int filecount = 1;
string filename = "testfilename";
string networkDirectory = #"c:\fakepath\";
string fileToRead = #"c:\fakepath\textfile.txt";
using (StreamReader reader = new StreamReader(fileToRead,Encoding.Default,true))
{
while (reader.Peek() > 0)
{
using (StreamWriter writer = new StreamWriter(Path.Combine(networkDirectory, filename + filecount + ".txt"), true, Encoding.Default))
{
writer.Write(reader.ReadLine());
}
reccount++;
// checks on each iteration of the while loop to see if the
// current record count matches the number of records per file
// if sso reset reccount and change increment filecount to change the file name
if (reccount == recper)
{
reccount = 0;
filecount++;
}
}
}
Another way you can do this is in a dataflow:
First use your method of choice to add a "Row Number" column to your data flow (unless there is already one in your flat file output, in which case skip this step and use that):
https://www.google.com/search?sourceid=navclient&aq=&oq=add+rownumber+column+to+ssis+dataflow&ie=UTF-8&rlz=1T4GGNI_enUS551US551&q=add+rownumber+column+to+ssis+dataflow&gs_l=hp....0.0.0.6218...........0._Qm62-0x_YQ
Then add a MultiCast transformation to your dataflow, and use the row number to split the stream and send it to different destinations:
Row 1 - 55k, -> File1
Row 55001 - 110k -> File2
etc.

How Can I paste the content of a text file 400 times

its for a unity research project, I dont want to have to press control v exactly 400 times. I just want to paste it in another .txt file
this is the text
http://pastebin.com/m1u4AFAr
Thank you for you help
Use Unity. Go to that link and copy the text. Run this script in Unity and it will duplicate the text for 400 times and save it. It will show you where it saved it. Any text you have in the clipboard will be duplicated 400 times.
void Start()
{
//Get Clipboard
string fileInfo = GUIUtility.systemCopyBuffer;
if (fileInfo == null)
{
Debug.Log("Clipboard is Empty. Exited");
return; //exit
}
//Multiply by file 400
System.Text.StringBuilder crazyfileX400 = new System.Text.StringBuilder();
for (int i = 0; i < 400; i++)
{
crazyfileX400.Append(fileInfo).Append("\r\n");
}
string filename = Application.persistentDataPath + "/" + "crazyFile.txt";
System.IO.File.WriteAllText(filename, crazyfileX400.ToString());
Debug.Log("File written to " + filename);
}
Have a look at this open source macro-creation and automation software.
You can use it to write a script that does the job for you. Here's a a script for simple copy and paste:
#c::
Send, {CTRLDOWN}c{CTRLUP}{ALTDOWN}{TAB}{ALTUP}
sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{ENTER}{ALTDOWN}{TAB}{ALTUP}
return
You could adapt it to your situation by adding a loop.

How to insert/replace string value into another string value at certain place?

This is an uploading tool. I am trying to rename a file name if it is existed in the folder already.
The plan is to add a number after the file name. For example, if the file name is Hello.doc, it will be saved as Hello2.doc.
The problem is, the file name & file type are always different. It can be Goodbye.pdf/capture.png. I am not sure how to insert the number in the correct place.
if (System.IO.File.Exists(savepath))
{
int counter = 2;
while (System.IO.File.Exists(savepath))
{
string newFileName = fileName + counter;
tempFileName = newFileName.Insert/replace //Not sure what to do here
savepath += tempFileName;
counter++;
}
FileUpload.SaveAs(savepath);
lblUpload.Text = "A file with the same name already exists." + " Your file was saved as " + tempFileName;
}
Does someone know? Thanks!
Please let me know if this is what you were looking for. Used StringBuilder to avoid creating new String objects after every concatenation.
String[] filepath = filename.split(".");
// filepath[0] -> filename
// filepath[1] -> extension
StringBuilder newFilename = new StringBuilder(filepath[0]);
// add number
newFilename.append(2);
// add period
newFilename.append(".");
// add extension
newFilename.append(filepath[1]);
return newFilename.toString();

How to use two different outputs of one TV in MODX?

I have TV with input type "File". How can i use output of this file few times:
1. in one place as url
2. in one place as name of this file
3. in one place as size of this file
Thank you
1 - use your tv - My File
2 - use snippet like this -
[[!getNameFromPath?&path=`[[*myFileTv]]`]]
and code of this snippen is -
<?php
$path = $modx->getOption('path', $scriptProperties, '');
$fileName = basename($path);
return $fileName;
3 - use another snippet -
[[!getSizeFromPath?&path=`[[*myFileTv]]`]]
which code is -
<?php
$path = $modx->getOption('path', $scriptProperties, '');
if (!empty($path)) {
$size = filesize(MODX_BASE_PATH . ltrim($path,'/'));
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
if ($size == 0) {
return('n/a');
} else {
return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
}
}
You will have to create a snippet to output the parameter you want.. something like:
[[!outputMyFile? &attribute=name &tv=[[*myTvValue]]]]
where the snippet will do your processing on the TV value [the file name] and output the appropriate attribute you want.

Sharepoint 2010 How to use "File Size" column value in a formula?

I am trying to use "File Size" (aka "FileSizeDisplay") in a Calculated column formula.
"File Size" is an existing column (default SP not custom).
But is not available in the "Insert Column" list of any library.
And SP displays an error message that states it does not exist if it is added to a formula manually as either [File Size] or [FileSizeDisplay].
All I want to do is inform a user that an image is too big. Not trying to prohibit file size upload or anything technical like that. Just want a Calculated column to display a message.
If the column value was available the following would work:
=IF([File Size]>50000,"Image is too big","Image is sized correctly")
or
=IF([FileSizeDisplay]>50000,"Image is too big","Image is sized correctly")
Any one know why this column is not available?
Cheers
You'll want to get the file size first: get file size then you can display of message in a pop up or how ever you'd like
using System;
using System.IO;
class Program
{
static void Main()
{
// The name of the file
const string fileName = "test.txt";
// Create new FileInfo object and get the Length.
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
// Change something with the file. Just for demo.
File.AppendAllText(fileName, " More characters.");
// Create another FileInfo object and get the Length.
FileInfo f2 = new FileInfo(fileName);
long s2 = f2.Length;
// Print out the length of the file before and after.
Console.WriteLine("Before and after: " + s1.ToString() +
" " + s2.ToString());
// Get the difference between the two sizes.
long change = s2 - s1;
Console.WriteLine("Size increase: " + change.ToString());
}
}

Resources