I am trying to write content in a file from terminal. File is creating but content is not written into the file.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(int argc, char *argv[])
{
FILE *fp;
fp=fopen(argv[1],"w");
char ch;
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
return 0;
}
If you don't signal EOF (Ctrl+Z in Windows and Ctrl+D in Linux), then the loop will continue to execute until it receives that signal.
If you attempt to read the file with your own eyes while the program is still on execution, then the file stream will not have close (fclose(fp); will not have execute), thus the file will appear to you empty, even though the content will be shown to you, when the file stream closes.
The following works fine:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(int argc, char *argv[])
{
FILE *fp;
fp=fopen(argv[1],"w");
char ch;
while(1)
{
ch = (char)getchar();
putc(ch,fp);
if(ch == '.') break;
}
fclose(fp);
return 0;
}
Related
Here is my code but I don't know why it prints only some part of lines.
here is my code:
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
FILE *fpr,*fpw;
int cnt=0;
fpw=fopen(argv[2],"w+");
char buff[1000];
while((fpr=fopen(argv[1],"r"))==NULL)
{
printf("\nCan't open file %s\n",argv[1]);
scanf("re-enter file name:%s\n",argv[1]);
}
while (!feof(fpr))
{
fgets(buff,2,fpr);
if(buff[0]=='\n')
{
putc(buff[0],fpw);
fseek(fpw,0,SEEK_SET);
}
fputs(buff,fpw);
cnt++;
}
fclose(fpr);
fclose(fpw);
}
INPUT FILE:
Hrey yhis will print twicw
lets print thrice
#why not
OUTPUT FILE
lets print thrice
#why not
So.. basically what I was trying to do is actually impossible using lseek/fseek. So I found another approach , as shown in the code below:
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
FILE* fr;
FILE* fw;
int l=0;
char lines[10000][100];
if( ( (fr=fopen(argv[1],"r+"))==NULL || (fw=fopen(argv[2],"w+"))==NULL ) )
{
printf("Error reading or opening files %s,%s",argv[1],argv[2]);
}
while(fgets(lines[l++], sizeof(lines[l]), fr)!=NULL);
while(l>=0)
fputs(lines[l--],fw);
fclose(fr);
fclose(fw);
}
I need to write a program that asks the user to enter strings, each string ends when the user presses 'Enter'.
The program needs to receive the file name as a parameter, the file should be opened and closed for each operation and for every string entered, the program should append the string to the end of the file (on a new line).
This is my code so far:
int is_file_exists(char *file_name)
{
FILE *file;
if ((file = fopen(file_name,"r"))!=NULL)
{
/* file exists */
fclose(file);
return 1;
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
return 0;
}
}
int main(int argc, char **argv)
{
char c;
FILE *file;
if (argc >= 2)
{
if (is_file_exists(argv[1]))
{
file = fopen(argv[1], "w");
}
else
{
return 0;
}
}
else
{
file = fopen("file.txt", "w");
}
while ((c = getchar()) != EOF)
{
putc(c, file);
}
return 0;
}
So far the code compiles and file is being created, but nothing is being written inside of it.
Edit: I also need some function pointers, see my comments on selected answer
I think one of the problem was that you were opening and closing a file, and then reopening it subsequently. It is better to just leave it open using a pointer while simultaneously testing that there were no issue to open the file. Another problem was that you were writing in the file, don't you prefer to append text to it? Well it's your decision. As for the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // exit
typedef struct mystruct {
char *exit_word;
void (*exit_fptr)(int); // man exit
int (*strcmp_fptr)(const char *, const char*); // man strcmp
} t_mystruct;
int is_file_exists(char *filename, FILE **file)
{
return (*file = fopen(filename,"a")) > 0;
}
#define BUFF_SIZE 1024
int main(int argc, char **argv)
{
char c;
FILE *file;
t_mystruct s = {.exit_word = "-exit", .exit_fptr = &exit, .strcmp_fptr = &strcmp};
if (argc >= 2) {
if (!(is_file_exists(argv[1], &file)))
return 0;
}
else
file = fopen("file.txt", "a"); // open the file in append mode
char buffer[BUFF_SIZE];
while (42) {
int i = 0;
memset(buffer, 0, BUFF_SIZE);
while ((c = getchar()) != '\n')
buffer[i++] = c;
if (!s.strcmp_fptr(buffer,s.exit_word)) {// exit if user type exit, allow you to fclose the file
fclose(file);
s.exit_fptr(EXIT_SUCCESS); // better to use the define
}
buffer[i] = '\n';
fputs(buffer, file);
}
fclose(file);
return 0;
}
your code can work
remember to press Ctrl+d when finished input. the file will have the content your expected
your code wait for EOF to quit the loop. Ctrl+d is a way to input EOF, or else the program never ends.
putc will write to cache at first, then write to disk. this an optimization mechanism of File System. you can choose to avoid this by DirectIO when open file.
when program terminate normally, file will be closed automatically, then data in cache will be copy to disk;
but when program terminated abnormally, data in cache might be lost.
file should be closed
fclose is needed.
open and close should be organized in pair just as malloc and free.
I was trying to code a c program that is given the name of a file by Command line and then opens the nano editor on the file through a system() call.
After having edited and saved the file, the c program sorts the file by first reading the file, sorting the contents and then writing to the file.
But I am getting segmentation error. Please help.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argcn,char **args)
{
char *filename=*(args+1);
char *command="nano";
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
system(command);
int numbers[100];
int n=0;
FILE *fp;
fp=fopen(filename,"r+");
while(1>0)
{
int num;
int x=fscanf(fp,"%d",&num);
if(x!=1)
break;
else
{
numbers[n]=num;
n+=1;
}
}
numbers[n]=-1;
int temp;
int temp1;
for(temp=0;temp<(n-1);temp++)
{
for(temp1=(temp+1);temp1<n;temp1++)
{
if(numbers[temp1]<numbers[temp])
{
int t=numbers[temp1];
numbers[temp1]=numbers[temp];
numbers[temp]=t;
}
}
}
fclose(fp);
FILE *nfp;
nfp=fopen(filename,"w");
for(temp=0;temp<n;temp++)
{
fprintf(nfp,"%d\n",numbers[temp]);
}
fclose(nfp);
}
This code can lead to undefined behaviors
char *command="nano";
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
Because command is 5 byte length filled with "nano\0" and you appending space " " and filename to memory after 'allocated' place.
You need pre allocate command enough to hold nano command with file name. For example you can try:
char command[256];
strcat(command,"nano");
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
When I try to read input from a file named "file1", my program correctly displays
the number of characters in the file, but in an unrecognized character format.
Below is the code
#include <stdio.h>
#include <stdlib.h>
void db_sp(FILE*);
int main(int argc,char *argv[])
{
FILE *ifp,*ofp;
if(argc!=2) {
fprintf(stderr,"Program execution form: %s infile\n",argv[0]);
exit(1);
}
ifp=fopen(argv[1],"r");
if (ifp==NULL) printf("sdaf");
//ofp=fopen(argv[2],"w+") ;
db_sp(ifp);
fclose(ifp);
//fclose(ofp);
return 0;
}
void db_sp(FILE *ifp)
{
char c;
while(c=getc(ifp) !=EOF) {
//printf("%c",c);
putc(c,stdout);
if(c=='\n' || c=='\t' || c==' ')
printf("%c",c);
}
}
The problem is here:
while(c=getc(ifp) !=EOF){
Because of operator precendence, this getc(ifp) !=EOF gets executed first. Then c = <result of comparison> gets executed. Which is not the order you want.
Use parentheses to force the correct order.
while((c=getc(ifp)) !=EOF) {
Other notes:
getc returns an int so you should change the type of c to int.
Also, if you fail to open the file, you still continue execution. You should gracefully exit on failure.
So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}