• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

write to a file

Hi,
   How can I write a couple of lines to a file using c?
ex:  I want a simple c program which will write three lines to a file call
/tmp/file1 under solaris.

after I run the c program, it should write the three lines to the /tmp/file1

/tmp/file1 contains:
#! is line one
line2
line3 is good

thanks in advance
0
siunix
Asked:
siunix
1 Solution
 
kotanCommented:
FILE *fptr;

fptr = fopen("w", "/tmp/file1");

fprintf(fptr, "#! is line one");
fprintf(fptr, "line2");
fprintf(fptr, "line3 is good");

fclose(fptr);
0
 
ShivshankarCommented:
void g()
{
  FILE * f;
  f = fopen("/tmp/file1", "w");
  //Code for writing into the file
  //goes here...
  fclose(f);
}
0
 
tapasmondalCommented:
There are two options:
1. You want to creat a new file which having only these threee lines.
2. You want to add these threee lines in a existing file.


for 1. you will have to open this file in write mode.
like as follow:

void file_to_write()
{
FILE *fin;
fin = fopen("/tmp/file1","w");
fprintf(fin, "#! is line one");
fprintf(fin, "line2");
fprintf(fin, "line3 is good");

fclose(fin);
}

for 2. you will have to open this file in append mode.
like as follow:

void file_to_write()
{
FILE *fin;
fin = fopen("/tmp/file1","a");
fprintf(fin, "#! is line one");
fprintf(fin, "line2");
fprintf(fin, "line3 is good");

fclose(fin);
}



If you want to creat in binary mode, you have to replace "w" by "wb" and "a" by "ab".

Thanking you

tapas

0
 
siunixAuthor Commented:
great answer.
thanks for all your help.
0
 
siunixAuthor Commented:
I try:
fprintf(fptr, "fi");

and it does not write "fi" to the file.
is there a fix for this?


thanks


0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now