Compiler executing if statement randomly - c

I have following C program:
#include <stdio.h>
int main()
{
char *filename;
FILE *fp1, *fp2;
int i, number;
fp1=fopen("TEST", "w");
for(i=10; i<=100; i+=10)
{
putw(i, fp1);
}
fclose(fp1);
printf("\nInput filename\n");
open_file:
scanf("%s", filename);
if((fp2=fopen(filename, "r"))==NULL)
{
printf("Cannot open the file.\n");
printf("Type file name again.\n");
goto open_file;
}
else
{
for(i=1; i<=20; i++)
{
number=getw(fp2);
if(feof(fp2))
{
printf("\nRan out of data\n");
break;
}
else
{
printf("%d\n", number);
}
}
fclose(fp2);
}
return 0;
}
I inputed TEST for scanf("%s", filename);. But this statement if((fp2=fopen(filename, "r"))==NULL) is always executing and my compiler is printing Cannot open the file Type file name again randomly. Here is a goto statement. So it should wait for another input. But it is not. Where is the problem??

char *filename; is a pointer and no memory is allocated for it.
Try
char filename[100]; and give valid file name to work.

Problem is scanf("%s", filename); .
As filename is char pointer which is not allocated in your program (this non allocated pointer leads to undefined behavior). So you can either allocated pointer or use char array.

From here scanf, when you write scanf("%s", filename);, means you want to read an string and store the sting into filename, so the filename must be a arry(you should allocate memory for storing the string), but in you code you just write char *filename;, you don't allocate memory.

Related

Cannot write/read string separated by coma into a file

I'm trying to write a set of parameters of a structure into a file, and then read it in the program. The structure has a int type variable and a string type variable(this string is separated by space). I've successfully written and then read the integer part of the structure, but when i try to do the same for the string, the program crashes. I think it has something to do with my the fprintf statement, and trying to read a string separated by space.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
int main(void) {
// creating a FILE variable
FILE *fptr;
// integer variable
int i = 0;
char n[50];
// character variable
struct cliente {
char nome[50];
int nif;
};
struct cliente client[0];
// open the file in write mode
fptr = fopen("student", "w");
if (fptr != NULL) {
printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
// exit status for OS that an error occured
return -1;
}
// get student detail
printf("Enter student name: ");
scanf(" %[^\t\n]c", client[1].nome);
printf("Enter student ID: ");
scanf("%d", &client[1].nif);
// write data in file
fprintf(fptr, "%d %s", client[1].nif, &client[1].nome);
// close connection
fclose(fptr);
// open file for reading
fptr = fopen("student", "r");
// display detail
printf("\Ficheiro:\n");
fscanf(fptr, "%d %s", &i, n);
printf("ID: %d\n", i);
printf(" %s", n);
// close connection
fclose(fptr);
return 0;
}
You are declaring an array of zero length (struct cliente client[0]) but referencing the second element in the array (client[1]). That could cause a crash.

Segmentation fault while file copy in unix

I am writing to copy text from one file to another in unix using C lang. Below is a a part of my code. when i execute the program i am getting Segmentation fault error.
Any help appreciated..
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main (int argc, char *argv[])
{
char buffer[BUFFSIZE];
int infile;
int outfile;
int n;
size_t size;
printf("Enter the Source file name: \n");
scanf("%s",&argv[1]);
printf("Enter the Destination file name : \n");
scanf("%s", &argv[2]);
if((infile = open(argv[1], O_RDONLY,0)) < 0)
{
perror("Source file does not exist");
return -1;
}
if((outfile=open(argv[2],O_WRONLY,0644))>0)
{
printf("Target/Destination File Exists:\n \n ");
//printf("Target Fiel Exists , Do you wish to Overwrite or Appened Data to it: \n \n 1=Yes(Overwrite),\n 0=No(Append):\n");
scanf("%d",&n);
if(n==1)
{
if((outfile=open(argv[2],O_WRONLY|O_CREAT |O_EXCL, 0644)>=0))
{
printf("File is Being opened in Overwrite Mode: \n \n");//File is overwrited
}
}
}
}
It's very, very unusual to read data into your argv array. You probably shouldn't think about doing that.
Even if you really wanted to do that, the following would still be wrong:
scanf("%s",&argv[1]);
The elements of argcv are pointers to strings, so that function call will read a string into the memory that stores a pointer. The argv[1] elemetn will be invalid, adn in all likelihood the string that is input will overrun and trash one or more elements after that one.
Try something like:
char infile_name[81];
char outfile_name[81];
printf("Enter the Source file name: \n");
scanf("%80s", infile_name);
printf("Enter the Destination file name : \n");
scanf("%80s", outfile_name);
And adjust the rest of the references to argv[1] and argv[2].

fprintf not working, need to print specific lines of txt file

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
struct info
{
char name[15];
char surname[15];
char gender[15];
char education[15];
} sem;
FILE *fp=NULL;
int i, a;
char tmp[256] = {0x0};
while(1)
{
printf("Enter the value\n");
scanf("%d", &a);
if((fp = fopen("info.txt", "r")) != NULL)
{
switch(a)
{
case 0:
exit(0);
case 1:
for(i=0;!feof(fp);i++)
{
fscanf(fp, "%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);
printf("%s, %s, %s, %s\n",sem.name,sem.surname,sem.gender,sem.education);
}
break;
case 2:
while (fgets(tmp, sizeof(tmp), fp) != NULL)
{
if (strstr(tmp, "bachelors"))
{
/* Code works fine until this part */
fprintf(fp, "\n%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);
}
}
break;
default: printf("Default statement");
}
fclose(fp);
}
}
}
If anyone could point me out what im doing wrong, id be very greatful, I added a comment where code runs in to a problem and doesnt display anything. Basicly i have txt file. Program if user so desires needs to find lines in the file where "bachelor" is typed and give me back all of those lines.
You are opening your file in read mode (fp = fopen("info.txt", "r")) and trying to write in it using fprintf() which is not possible.
Use fp = fopen("info.txt", "r+") i.e read and write mode.
If you want to compare strings, you will have to use strcmp(), not an undefined function like "strstr". Also, strcmp returns 0 if two strings have same value. So you also have to check that the return value of strcmp() is zero or not.
Also as I replied to your question yesterday, fprintf() method appends the characters that you've passed as arguments to file. So, in your code, when you find string "bachelor", you just add same line at the end of the file. If you want to see those data in console, you can use printf() method.

File name string errors

I'm having a little trouble with the code below and I can not for the life of me figure out what went wrong and why it is displaying what it does, any help or assistance would be most appreciated. It is supposed to allow 5 lines of text to be entered and display those 5 lines onscreen, however it only allows 4 lines to be entered, and 4 are displayed. Please help!
#include <stdio.h>
int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
scanf("%s",filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
printf("unable to open File");
}
for(n=1;n<6;n++)
{
printf("\nEnter line %d:",n+1);
gets(string);
fputs(string,fp);
fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
printf("unable to open File");
}
for(n=1;n<6;n++)
{
fgets(string,100,fp);
printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}
The problem is that scanf("%s", filename); doesn't consume the newline after the filename. So your first call to gets() reads this newline as an empty line.
Add:
gets(string);
after that line to use up the rest of the line before you start reading input lines.
Here is the modified code. Added gets instead of scanf and added return 0; if file is not opened.
#include <stdio.h>
int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
gets(filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
printf("unable to open File");
return 0; // do not proceed
}
for(n=1;n<6;n++)
{
printf("\nEnter line %d:",n);
gets(string);
fputs(string,fp);
fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
printf("unable to open File");
return 0; // do not proceed
}
for(n=1;n<6;n++)
{
fgets(string,100,fp);
printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}
replace scanf("%s",filename) with gets(filename)
To get rid of the newline in the buffer right after your call to scanf, you can simply add getchar();:
scanf("%s", filename);
getchar();
But do adjust your for loops to start at 0, since you add 1 to n i.e:
for(n=0;n<6;n++)
^
After making those changes I was able to input 6 lines and then print all of them out.
As you've noticed, buffered input can be pesky if you don't deal with it properly as it can be inserted in your subsequent input calls. Don't be tempted to flush the stdin.
Here are some recommended alternatives on how to deal with this.

Not able to read file using C

Here is the code I have:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,a[40];
char file_name[100];
FILE *file;
printf("enter the file name\n");
scanf("%s",&file_name);
printf("enter the size\n");
scanf("%d",&n);
if((file=fopen(file_name,"rb"))==NULL)
{
printf("cant open a file\n");
return;
}
fread(a,sizeof(int),n,file);
for(i=0;i<n;i++)
{
printf("%s",a[i]);
}
}
Change:
scanf("%s",&file_name);
to:
scanf("%s", file_name);
You also need to change:
printf("%s",a[i]);
to:
printf("%d", a[i]);
(and while you're at it, change void main to int main).
scanf("%s",&file_name);
you don't have to pass a pointer to file_name since it's already a pointer. Change this line to:
scanf("%s", file_name);

Resources