Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read and edit a .txt file in C#?

For example, I have a txt file that reads:

12 345 45
2342 234 45 2 2 45345
234 546 34 3 45 65 765
12 23 434 34 56 76 5

I want to insert a comma between all the numbers, add a left brace to the begining of each line and a right brace to the end of each line. So after the editing it should read:

{12, 345, 45}
{2342, 234, 45, 2, 2, 45345}
{234, 546, 34, 3, 45, 65, 765}
{12, 23, 434, 34, 56, 76, 5}

How do I do it?

like image 772
George Powell Avatar asked Sep 02 '09 15:09

George Powell


People also ask

How do you read and write from a file in C?

For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.

Can you edit .txt files?

TXT Plain Text File FormatA standard text document can be opened in any text editor or word processing application on different operating systems. All the text contained in such a file is in human-readable format and represented by sequence of characters.


1 Answers

Added some LINQ for fun and profit (room for optimization ;) ):

System.IO.File.WriteAllLines(
    "outfilename.txt",
    System.IO.File.ReadAllLines("infilename.txt").Select(line =>
        "{" +
        string.Join(", ",
            line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
        ) + "}"
    ).ToArray()
);
like image 183
aanund Avatar answered Nov 08 '22 21:11

aanund