#include<stdio.h>
#include<stdlib.h>
void main(){
FILE *fp;
char str[20];
fp=fopen("krishna.txt","a");
if(fp==NULL)
printf("File not exist");
exit(1);
printf("Enter the strings:");
gets(str);
fputs(str,fp);
//fprintf(fp,"%s",str);
printf("Successfully print");
fclose(fp);
}
why it is not appending
i want this to append in my existing file name krishna
Use curly braces { } to surround multiple statements in a block.
Additionally, try using perror to better understand why things fail.
Do not use gets, please read: Why is the gets function so dangerous that it should not be used?
Use a proper signature for main: void main() is rarely correct. Use either int main(int argc, char **argv) if you want to use program arguments, or int main(void) if you do not.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[128];
FILE *fp = fopen("krishna.txt", "a");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
printf("Enter a line of text: ");
if (fgets(str, sizeof str, stdin) && fputs(str, fp) > 0) {
puts("Line appended to file.");
} else {
perror("fgets/fputs");
}
fclose(fp);
}
Related
I get the above error in CppCheck but I can't see what's wrong.I guess the error is the reason my code doesn't find any files,even if they exist in my computer.Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *getchoice(void);
void getfile(char *filename);
int main() {
char *choice;
choice=getchoice();
getfile(choice);
return 0;
}
char *getchoice(void) {
char *filename;
filename=malloc(SIZE);
printf("Enter the name of the text file: ");
scanf("%30s",filename);
return filename;
}
void getfile(char *filename) {
FILE *fp;
fp=fopen(filename,"r");
if (fp==NULL){
printf("The entered file does not exist.");
printf("\n");
}
else{
printf("The file exists.");
}
fclose(fp);
return;
}
Here is a list of things to do, in order to clean up this program:
Handle the event that malloc fails, so that scanf and getfile are not passed NULL.
Check that scanf successfully performed the expected number of conversions, to ensure filename contains valid data.
Use perror to give more accurate information about why malloc or fopen failed.
Avoid passing NULL to fclose, in the event that fopen failed.
free memory allocated by malloc (Unlike fclose, free may be safely passed NULL).
#include <stdio.h>
#include <stdlib.h>
char *getchoice(void);
void getfile(char *filename);
int main(void) {
char *choice = getchoice();
if (choice)
getfile(choice);
free(choice);
}
char *getchoice(void) {
char *filename = malloc(80);
if (filename) {
printf("Enter the name of the text file: ");
if (1 != scanf("%79s", filename)) {
free(filename);
return NULL;
}
} else {
perror("malloc");
}
return filename;
}
void getfile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp) {
puts("File opened.");
fclose(fp);
} else {
perror("fopen");
}
}
Check for a word in a text file line by line and when you found it,print the whole line,the program receives as command line argumets the text file and the word you are searching for.
Here is what I've tried to do so far,but I have segmentation fault and I don't really know what I'm supposed to do.
int main(int argc, char const *argv[])
{
FILE *file;
if(argc!=3)
{
printf("error 1");
exit(1);
}
if((file=fopen(argv[1],"r"))==NULL)
{
printf("Error");
exit(1);
}
char line[100];
char *p;
while(!feof(file))
{
fgets(line,sizeof(line),file);
p=strtok(line," ");
while(strcmp(p,argv[2])!=0)
p=strtok(NULL," ");
if(strcmp(p,argv[2])==0)
{
printf("%s",line);
}
}
fclose(file);
return 0;
}
You are doing strcmp(p,argv[2]) without checking p is NULL. You should check that.
Also your usage of while(!feof(file)) is wrong. You should check if readings succeeded before using what are "read".
Fixed code:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *file;
if(argc!=3)
{
printf("error 1");
exit(1);
}
if((file=fopen(argv[1],"r"))==NULL)
{
printf("Error");
exit(1);
}
char line[100];
char *p;
while(fgets(line,sizeof(line),file)) /* check if reading succeeded */
{
p=strtok(line," ");
while(p!=NULL && strcmp(p,argv[2])!=0) /* check if p is not NULL */
{
p=strtok(NULL," ");
}
if(p!=NULL && strcmp(p,argv[2])==0) /* check if p is not NULL */
{
printf("%s",line);
}
}
fclose(file);
return 0;
}
How to redirect more than one text file in c program? For example I have the following C code:
//redirection.c
#include<stdio.h>
main()
{
int x,y;
scanf("%d",&x);
x=x*x;
printf("%d",x);
scanf("%d",&y);
y=x+y;
printf("%d",y);
}
After compiling this code I created two text files text1.txt having the value 8 and text2.txt having the value 6.
When I give input to this program using command line redirection (as redirection<text1.txt), it gives output 64 and does not wait to take another input (and program exits) which I want to give another input from text2.txt.
Is there any solution how can I send another input via text2.txt for second scanf function in the above program?
While giving the input as redirection as like this.
cat a b | ./a.out.
Or else you can use the command line arguments.
#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fp, *fp1;
if ( (fp=fopen(argv[1],"r")) == NULL ){
printf("file cannot be opened\n");
return 1;
}
if (( fp1=fopen(argv[2],"r")) == NULL ){
printf("file cannot be opened\n");
return 1;
}
int x,y;
fscanf(fp,"%d",&x);// If you having only the value in that file
x=x*x;
printf("%d\n",x);
fscanf(fp1,"%d",&y);// If you having only the value in that file
y=x+y;
printf("%d\n",y);
}
you can also use command line arguments:
#include <stdio.h>
#define BUFSIZE 1000
int main(int argc, char *argv[])
{
FILE *fp1 = NULL, *fp2 = NULL;
char buff1[BUFSIZE], buff2[BUFSIZE];
fp1 = fopen(argv[1], "r");
while (fgets(buff1, BUFSIZE - 1, fp1) != NULL)
{
printf("%s\n", buff1);
}
fclose(fp1);
fp2 = fopen(argv[2], "r");
while (fgets(buff2, BUFSIZE - 1, fp2) != NULL)
{
printf("%s\n", buff2);
}
fclose(fp2);
}
here is a more cleaned up version:
#include <stdio.h>
#define BUFSIZE 1000
void print_content(char *file);
int main(int argc, char *argv[])
{
print_content(argv[1]);
print_content(argv[2]);
}
void print_content(char *file){
char buff[BUFSIZE];
FILE *fp = fopen(file, "r");
while (fgets(buff, sizeof(buff), fp) != NULL)
{
printf("%s\n", buff);
}
fclose(fp);
}
My code is like a text compressor, reading normal text and turns into numbers, every word has a number. It compiles in DevC++ but does not end, however, it does not compile in Ubuntu 13.10. I'm getting an error like in the title in Ubuntu "undefined reference to `strlwr'", my code is a little long so I am not able to post it here, but one of the error is from here:
//operatinal funcitons here
int main()
{
int i = 0, select;
char filename[50], textword[40], find[20], insert[20], delete[20];
FILE *fp, *fp2, *fp3;
printf("Enter the file name: ");
fflush(stdout);
scanf("%s", filename);
fp = fopen(filename, "r");
fp2 = fopen("text.txt", "w+");
while (fp == NULL)
{
printf("Wrong file name, please enter file name again: ");
fflush(stdout);
scanf("%s", filename);
fp = fopen(filename, "r");
}
while (!feof(fp))
{
while(fscanf(fp, "%s", textword) == 1)
{
strlwr(textword);
//some other logic
}
}
.... //main continues
strlwr() is not standard C function. Probably it's provided by one implementation while the other compiler you use don't.
You can easily implement it yourself:
#include <string.h>
#include<ctype.h>
char *strlwr(char *str)
{
unsigned char *p = (unsigned char *)str;
while (*p) {
*p = tolower((unsigned char)*p);
p++;
}
return str;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strlwr(char* );
int main()
{
printf("Please Enter Size Of The String: \n");
int a,b;
scanf("%d",&a);
char* str;
str=(char*)malloc(sizeof(char)*a);
scanf("\n%[^\n]",str);
char* x;
x=strlwr(str);
for(b=0;x[b]!='\0';b++)
{
printf("%c",x[b]);
}
free(str);
return 0;
}
char* strlwr(char* x)
{
int b;
for(b=0;x[b]!='\0';b++)
{
if(x[b]>='A'&&x[b]<='Z')
{
x[b]=x[b]-'A'+'a';
}
}
return x;
}
I am new to programming and have a few questions as to how to implement this idea.
I am looking to have a user enter their name/string of digits and if their name is on a list, to then execute a string of commands. I am not to sure how to impliment this, but with some gogle-ing I was able to come up with this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char userName[10];
printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
if (fp == John) {
//Dispence squence of pills for John
}
if (fp == Mary) {
//Dispence squence of pills for Mary
}
return 0;
}
I do not think I am using the if statement correctly. how can I do something like:
if (content in fp == john, execute/call another function)
Thanks in advance!
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}
return 0;
}
fopen simply opens a file for reading and/or writing, to read the actual content of the file you need to use functions such as fgets, fscanf and so on.
Short example
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
char name[64];
char buffer[64];
printf ("Please enter your name: ");
file = fopen ("results.dat", "rw");
if (!file) {
printf ("Results.dat could not be opened.\n");
exit(-1);
}
if ( fgets (buffer, 64, file)) {
if (strcmp (buffer, "john")) {
printf ("Contents of file is john\n");
}
}
return 0;
}