LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Write to file (https://www.linuxquestions.org/questions/programming-9/write-to-file-373011/)

omerlh 10-14-2005 09:22 AM

Write to file
 
Hello!
I wnat to know how can I write into a file with any editor, than, the program can add a line at this file in place that was determined by me.
I try to find out at the net how to do it, but I find out just how to open file. I try to search here, and I don't find answere.

bigearsbilly 10-14-2005 09:42 AM

example?

using what? C or a unix tool or don't care?

omerlh 10-15-2005 11:30 AM

i mean, that the program get a string from the user, than,.it can open a file, put the string in line number x. That's all.
What you mean? How I do it in the program? From what I read use C is faster.

destuxor 10-15-2005 12:52 PM

The "sed" UNIX command can do that. It's not easy to get your mind wrapped around, but once you understand how to use sed it'll be a lot more useful to you than writing a single program to perform exactly one function.

omerlh 10-15-2005 01:34 PM

I need to do it in linux. I need it for program that can get from user something like:
3*pow(x, 2)+2x -4=y.
And the program can take that thing, and solve it. I know how to solve it, the problem is how to use the string. I thugh on writing it in file, that solve it.
So I want to know how to do it in C.

bigearsbilly 10-17-2005 03:39 AM

what is it for? business or pleasure.

you'll need to write a parser.
If you don't know C it will not be easy.
It's not a beginner problem.

what about using dc

destuxor 10-17-2005 04:02 AM

Personally, I prefer Perl. In this case, C would work and might even be an appropriate choice, but Perl is much safer and almost as fast (use google if you want to find comparison data, but I can tell you for a program like this the difference isn't significant).

In Perl (note that I didn't test this code, it should work fine, but if it doesn't tell me and I'll look at it):
Code:

#!/usr/bin/perl -w
use strict;
use warnings;

print "What file do you want to open/write to? ":
my $file = <stdin>;
print "What line to you want to insert text at? ";
my $line = <stdin>;
print "What text do you want to insert?? ";
my $text = <stdin>;

open (FH, $file) or die "Cannot open ".$file." for reading: $!\n";
my @allLines = <FH>;
close FH;

open (FH, "> ".$file) or die "Cannot open ".$file." for writing: $!\n";
my $lineNumber = 0;
for ( ; $lineNumber < $line ; $lineNumber++)
{
  print OUT $allLines[$lineNumber];
}

print OUT $text."\n";

for (; $lineNumber < $allLines ; $lineNumber++)
{
  print OUT $allLines[$lineNumber];
}

close OUT;



All times are GMT -5. The time now is 10:44 AM.