Segmentation fault while file copy in unix - c

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].

Related

I'm trying to write a specific number of lines in a file but I keep getting a blank line as the first one

i'm new here and i'm trying to solve a FILE problem in c. Basically i have to create a program that lets the user input how many lines he wants to write in a file, create a new file, write those lines and the reading it and establish how many lines where written and print the number of lines.
int main() {
int x, lc=0;
char str[100];
FILE *fp=fopen("test.txt","w");
if (fp==NULL) {
printf("\nOpening failed");
}else{
printf("\nOpened correctly");
}
printf("\nStrings to write:\n");
scanf("%d",&x);
for (int i = 0; i < x; i++) {
fgets(str, sizeof str, stdin);
fputs(str,fp);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL) {
lc++;
}
fclose(fr);
printf("\nThere are %d lines",lc);
return 0;
}
If i leave the code like this it messes up with my for cycle and it only lets me write 3 lines because it does put a free line at the start of the file. Can you explain how do i solve that? or if it's just how fgets and fputs behave and i have to remember that blank line at the start. Thank you in advance. (i'll leave a file output as follows with numbers for the lines)
1)
2)it seems to work
3)dhdhdh dhdh
4)random things
As you can tell from the comments, there are a lot of ways to approach this task. The usage of "scanf" and "fgets" can get complex especially if mixed within the same reading task. But, just to give you one option as to deriving a solution, following is a snippet of code to offer one of many possible routes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x, lc=0;
char str[101];
FILE *fp=fopen("test.txt","w");
if (fp==NULL)
{
printf("Opening failed\n");
}
else
{
printf("Opened correctly\n");
}
printf("Strings to write: ");
scanf("%d",&x);
for (int i = 0; i < x; i++)
{
printf("Enter string: ");
scanf("%s", str);
fprintf(fp, "%s\n", str);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL)
{
lc++;
}
fclose(fr);
printf("\nThere are %d lines\n",lc);
return 0;
}
You will note that both "scanf" and "fgets" are being used in this example, but not in reference to the same file. For user input, "scanf" is getting used. Once the file is closed and then reopened for reading, "fgets" is being used for that portion of the task.
Testing this program snippet out resulted in matching up the same quantity of lines read from the file as were entered.
#Una:~/C_Programs/Console/FileWrite/bin/Release$ ./FileWrite
Opened correctly
Strings to write: 4
Enter string: Welcome
Enter string: to
Enter string: Stack
Enter string: Overflow
There are 4 lines
Give it a try and see if it meets the spirit of your project.

Fwrite doesn't work properly

Sorry for having this program in my native language, but I really can't seem to find why it doesn't work. So, I tested and the values of the a array are all correctly read, but when I try to look at the .dat file there is only the first word read in the for function ( a[0].marca ).
Here is the input I also tested to see if it reads correct
Here is the .dat file It only writes the first
#include <stdio.h>
#include <stdlib.h>
struct data
{
int anul;
int luna;
};
typedef struct data DATA;
struct automobil
{
char marca[20];
char carburant;
char model[5];
DATA fabricatie;
};
typedef struct automobil AUTOMOBIL;
int main()
{
AUTOMOBIL a[100];
int n;
FILE *f;
int i;
if((f=fopen("evidenta.dat","wb"))==NULL)
{
exit(1);
}
printf("Cate automobile sunt ?"); scanf("%d",&n); // The number of cars registered
for(i=0;i<n;i++) // getting the details about every car
{
printf("\nMarca ? : "); fflush(stdin); gets(a[i].marca);
printf("\nCarburant ? : "); fflush(stdin); getch(a[i].carburant);
printf("\nModelul? :"); fflush(stdin); gets(a[i].model);
printf("\nLuna fabricatie ? :"); scanf("%d",&a[i].fabricatie.luna);
printf("\nAn fabricatie ? : "); scanf("%d",&a[i].fabricatie.anul);
// After getting a line it has to write it in the binary file
fwrite(&(a[i]),sizeof(AUTOMOBIL),1,f); //It writes only a[0].marca
}
for(i=0;i<n;i++)
{
printf("\n %s",a[i].marca);
printf("\n %c",a[i].carburant);
printf("\n %s",a[i].model);
printf("\n %d",a[i].fabricatie.luna);
printf("\n %d",a[i].fabricatie.anul);
}
return 0;
}
You have to do it this way:
fwrite(&(a[i]),sizeof(AUTOMOBIL),1,f);
Alternatively you can do that outside the loop:
fwrite(a,sizeof(AUTOMOBIL),n,f);
Also don't forget to fclose.
As the others answer say you need to write to &a[i]. If you want to see the contents of the file in the moment is written, you need to disable output buffer with setbuf(f, NULL) or flush it each time you write with fflush(f).
It's because you write the first item each time - &a while expecting &(a[i]) to be written.
And do not forget to fclose the file after writing for the buffer not to be lost.
If you want to see the live changes on the file while you write, you need to disable output buffer setbuf(f,NULL) or flush it fflush(f).

Run - Time Check Failure #2 in C File processing

Run-Time Check Failure #2 - Stack around the variable 'filename' was corrupted.
My code works whenever I try to process the first memory location.
I can process the .txt file correctly, and I can print it.
Nevertheless, when I ask for a second memory location, the program crashes.
I tried to increase the size of filename, and I am also closing the first file, so I am clueless. Any help is acceptable! Thank you!!
This is a photo of the output
This is my code:
#include <stdio.h>
#define SIZE 100 //100 entries (100lines on a file)
#define SENSORN 100
int main()
{
FILE *fptr;
char filename[1000];
char dummy1[1];//dummy character that help me to erase what is the buffer when using gets()
int numberOfSensors;
int time[SENSORN][SIZE];
float powerConsumption[SENSORN][SIZE];
int sensor_num;
int count1 = 0;
printf("Please enter the number of sensors: ");
scanf("%d", &numberOfSensors);
//Asking for the link
//numberOfSensors - 1 because for example, if we want only 2 sensors we need sensor0 and sensor1 only
for (sensor_num = 0; sensor_num <= (numberOfSensors - 1); sensor_num++)
{
printf("Please enter the file location for sensor %d\n", sensor_num);
gets(dummy1);//clearing the buffer
gets(filename);
fptr = fopen(filename, "r");
//if file cannot be opened, then display and error message
if (fptr == NULL)
{
printf("Error opening the file! %s \n", filename);
printf("Please restart the program \n");
return 0; //exit the program
}
else
{
//Loop that let us read and print all the file by storing each value to its respective array
while (!feof(fptr))
{
//storing all the values in their respective array
//sensor_num is the sensor number
//count1 is the line number we are reading from the file
fscanf(fptr, "%d %f", &time[sensor_num][count1], &powerConsumption[sensor_num][count1]);
//making sure we have all the values stored
//Note: do not comment the following line in order to check that all values are stored
fprintf(stdout, "%d %6.2f \n", time[sensor_num][count1], powerConsumption[sensor_num][count1]);
count1++;
}
}
//closing file
fclose(fptr);
}
}
}
As Martin James said char dummy1[1]; is an absolute no-no.
Use fgets() instead of gets(), so instead of
gets(dummy1);//clearing the buffer
gets(filename);`
try,
fgets( filename, sizeof(filename) , stdin );

Compiler executing if statement randomly

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.

Refining Spell Checker C program [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Compare two text files - spellchecking program in C
I am making a spellcheck program and have an operational code that works but really needs refinement.
Problem 1: I only want to read alphanumeric characters into the wordcheck array before comparing the strings. I want to get rid of all special characters. I think isalphnum would be the best option but not sure how to implement it.
Problem 2: Program is very slow and wasting a lot of memory. I don't know how else to do it though. Could anyone give me some pointers? I'm lost with using binary functions and that's what I'm sure I should be doing! Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
/*Open files and test that they open*/
FILE *fp1;
FILE *fp2;
char fname[20];
char wordcheck[45];/*The longest word in the English Language is 45 letters long*/
char worddict[45];
char dummy;
int i;
int notfound;
fp1 = fopen("dictionary.txt","r");
if (fp1 == NULL)
{
printf("The dictionary file did not open.");
exit(0);
}
printf("Please enter the path of the file you wish to check:\n");
scanf("%s", fname);
scanf("%c", &dummy);
fp2 = fopen(fname, "r");
if (fp2 == NULL)
{
printf("Your file did not open, please check your filepath and try again.\n");
printf("Please enter path of file you wish to check: \n");
scanf("%20s",fname);
fp2 = fopen(fname, "r");
}
else
{
printf("Your file opened correctly\n");
}
/*When files are open, read each word from the text file into an array:*/
while(fscanf(fp2,"%s", wordcheck)!=EOF)//Reads word from text file into array//
{
for (i=0; wordcheck[i]; i++)
{
wordcheck[i] = tolower(wordcheck[i]);//makes all characters lower case//
}
fseek(fp1,0,SEEK_SET);
/*printf("%s", wordcheck);//debugger*/
while(fscanf(fp1,"%s", worddict)!=EOF)
{
notfound = 1;
if(strcmp(wordcheck, worddict)==0)//compare strings//
{
printf("This word: %s is in the dictionary\n", wordcheck);//debugger//
notfound = 0;
break;
}
}
if(notfound == 1)
{
printf("%s is not in dictionary\n", wordcheck);
}
}
printf("Your file has been checked. Please check any errors found");
fclose(fp1);
fclose(fp2);
return 0;
}
You're reading the dictionary once for each input word! If your input file is long then load the dictionary first into memory and then check each word in the file. If the dictionary is long you may need to store it into a hash table or a trie. But even a simple array of dictionary words should give you an improved run time.

Resources