I a trying to take file name as argument and write strings using loop until user enter "-1".
problem 1: writing is not happening in text file and always shows empty
problem 2: cannot compare input -1 and "-1" . Always runs the else statements.
Note: I also tried fputs
but it did not work that time either.
FILE *fp = fopen(argv[1], "a");
//fseek(fp, 0, SEEK_END);
char str[100];
printf("enter string\n");
bool flag=true;
while(flag==true)
{
//printf("\nEnter data to append: ");
fflush(stdin);
fgets(str, 100, stdin);
if(strcmp(str, "-1")==0)
{
break;
}
else{
fprintf(fp, "%s",str);
printf("Text written in file: %s\n", str );
}
}
fclose(fp);
CodePudding user response:
Writing don't happen because of strcmp
, I'm showing you my version of this with atoi
.
#include <stdio.h>
#include <stdlib.h>
#define buffer 128
int main(int argc, char *argv[])
{
char str[buffer];
int flag = 1;
FILE *fp = fopen(argv[1], "w "); //I prefer using write mode and not append
if(fp==NULL)
{
printf("Error opening file.\n"); //here you control if the file is opening correctly
exit(EXIT_FAILURE);
}
while(flag) //you don't need to write while(flag==true) (that's not wrong)
{
printf("Insert string: ");
scanf("%s", str);
if(atoi(str)==1) //the function strcmp as you wrote it will break after the
break; //first cicle, use atoi, it returns 1 if the string is a number
fprintf(fp, "%s\n", str); //the \n is to get the next string on the next row
}
fclose(fp);
return 0;
}
CodePudding user response:
If you want to make it work with strcmp
your if statement should be if(strcmp(str, "-1\n"))
because fgets reads also the \n character.
CodePudding user response:
Because fget() reads new line character.
So once you do comparation, It looks like:strcmp("-1\n", "-1");
or
strcmp("-1\n\r", "-1");
You will never break the loop. To remove newline character, let try:
strtok(str, "\n");
or
strtok(str, "\r\n");