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);
Related
Well I have a problem using a function to write a string into a txt file, I just can't see why I can't print the string, when the program is in the function it just stop working.
This is the code creating a function passing the value by reference of the file and it works perfectly:
void saveTXT(FILE** txt,char *string)
{
fputs(string,*txt);
}
int main()
{
FILE * doc;
char string [10], singleline[50];
printf("Write the name of the file: \n");
scanf("%s",string);
fflush(stdin);
printf("Write the string to save into the file:\n");
scanf("%[^\n]",singleline);
doc = fopen(string,"w");
saveTXT(&doc,singleline);
fclose(doc);
return 0;
}
But when I go back to my project that has the same logic the program just closes:
void saveTXT(FILE** txt,node* n)
{
char buffer[100];
if(n == NULL)
fprintf(*txt,"*\n");
else
{
strcat(strcpy(buffer,n->data),"\n");
fflush(stdin);
printf("This is the string to be saved: %s\n",buffer);
fputs(buffer,*txt); //Problem
saveTXT(&(*txt),n->right);
saveTXT(&(*txt),n->left);
}
}
I made sure to open the file before and close it later, what I print is the string to be saved in the file, it shows the string and then crash, I just don't know why that happens.
There is no point in using double pointers here.
stdin cannot be flushed.
&(*txt) == txt
I think you struggle to understand what double pointers are for. You use them if you want to change the original pointer (single star one).
An example - the pointer fi will be modified in the function weirdopen:
void weirdopen(FILE **f, const char *filename)
{
*f = fopen(filename, "r");
}
void myread(FILE *f, char *str, const size_t size)
{
fgets(str, size, f);
}
int main(void)
{
FILE *fi;
char str[100];
weirdopen(&fi, "test.txt");
myread(fi, str, 100);
fclose(fi);
}
i am trying to create an program to generate empty files. but when it try to run the program it crashes after taking inputs from the console .
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int create(char* filename)
{
char filext[10];
printf("\nEnter File Extension :");
fgets(filext);
FILE* fp;
fp = fopen(strcat(filename,strcat(".",filext)),"w");
if(!fp)
{
return 0;
}
fclose(fp);
return 1;
}
int main(int argc , char* argv[])
{
int f;
int i;
char buffer[33];
if (argc == 3)
{
for(i = 0; i < atoi(argv[2]) ; i++)
{
f = create(strcat(argv[1],itoa(i,buffer,10)));
if(f==0)
{
printf("error in creating files . check uac!!!");
}
else{
printf("\nfile Created ...\n");
}
}
}
else{
printf("syntax Error");
}
return 0;
}
when I try to run this program I get the following output
F:\selfcreatedtools\filegen>gcc gen.c
F:\selfcreatedtools\filegen>a level 100
Enter File Extension :php
after entering the extension the program crashes.
i am a beginner in c programming.
Your main problem lies in the strcat(".",filext) part of fp = fopen(strcat(filename,strcat(".",filext)),"w");
Try
strcat(filename, ".");
strcat(filename, filext);
fp = fopen(filename, "w");
And it might be better if the function definition header was made
int create(char filename[SIZE]) (where SIZE is a value less than the size filename will be) instead of int create(char* filename) since you are using strcat() to modify the string in the user-defined function create(). You wouldn't want illegal memory accesses that would cause errors if the string encroaches upon the memory allotted to something else.
A similar problem is there with using strcat() to modify the string at argv[1] as pointed out by Jonathan Leffler for which BLUEPIXY has provided a solution in the comments.
I am trying to read an ASCII text file and write it into binary file. The text file is unlimited in size. First, I tried to read the text file before writing it. However, I keep getting segmentation fault. I don't understand what may cause the problem. Even using gdb, I still cannot figure out the problem. Please advise.
Code:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
typedef struct _FileData
{
int a;
double b;
char dataStr[56];
}FileData;
int main()
{
FILE * infile=fopen("output.txt", "r");
if(infile==NULL)
{
printf("Error opening file");
exit(1);
}
FileData **input;
int i=0;
while( fscanf(infile,"%d %f %[^\n]s",&input[i].a,&input[i].b,&input[i].dataStr)! =NULL)
{
printf("%d",input[i].a);
printf("%.3f",input[i].b);
printf("%[^\n]s",input[i].dataStr);
i++;
}
return 0;
}
My text file is
47
34.278
This is a line of text
48
23.678
This a very very long line
49
12.4569
This a very short line
50
117.906
This world is so beautiful
51
34.789
Hello world!
The problem in your code is that you have a pointer:
FileData** input;
You are using that pointer even though it's not been initialized to point to any valid memory.
Since you are writing the data out to stdout immediately after reading from the file, you can use:
FileData input;
while( fscanf(infile,"%d %lf %55[^\n]",&input.a, &input.b, input.dataStr) == 3)
// Notice the chage here
{
printf("%d",input.a);
printf("%.3f",input.b);
printf("%s\n",input.dataStr);
}
But then, I don't understand the need for struct _FileData. You can just as easily use:
int intValue;
double doubleValue;
char stringValue[56];
while( fscanf(infile,"%d %lf %55[^\n]",&intValue, &doubleValue, stringValue) == 3)
{
printf("%d %.3f %s\n",intValue, doubleValue, stringValue);
}
#include<stdio.h>
#include<ctype.h>
int main(int argc, char *argv[]) {
int i = 0;
char in[100], mychar[100];
FILE *file;
file = fopen(argv[1], "r");
fgets(mychar, 100, file);
while (in[i]) {
mychar[i] = in[i];
putchar(toupper(mychar[i]));
i++;
}
return 0;
}
I have another file named file.c and I write 'abcd' inside it.
This program will read a file's content and change them to capital letters. I don't know why when I typed
./a.out file.c
Nothing come out. What is wrong? I think maybe When using fopen(arg[1],"r") and fgets will make mychar as a string not array? Please have a look.Thanks.
You read the contents of the file into mychar, but test for the uninitialized in char array. To fix this you can just switch the arrays
while (mychar[i]) {
in[i] = mychar[i];
putchar(toupper(in[i]));
i++;
}
But you can also skip the copying and print the contents of mychar directly
while (mychar[i]) {
putchar(toupper(mychar[i]));
i++;
}
fgets(in,sizeof(in),file);
while (in[i]){
mychar[i]=toupper(in[i]);
putchar (mychar[i]);
I am trying to read name and password from a file into a structure in c, but clearly my code does not work as expected. Is there anyone can help me to figure out the problem with the codes attached below? Thanks a lot!
(Basically the file has several names and passwords, and I want to read them into a structure accounts[]`)
#include <stdio.h>
#include <stdlib.h>
struct account {
char *id;
char *password;
};
static struct account accounts[10];
void read_file(struct account accounts[])
{
FILE *fp;
int i=0; // count how many lines are in the file
int c;
fp=fopen("name_pass.txt", "r");
while(!feof(fp)) {
c=fgetc(fp);
if(c=='\n')
++i;
}
int j=0;
// read each line and put into accounts
while(j!=i-1) {
fscanf(fp, "%s %s", accounts[j].id, accounts[j].password);
++j;
}
}
int main()
{
read_file(accounts);
// check if it works or not
printf("%s, %s, %s, %s\n",
accounts[0].id, accounts[0].password,
accounts[1].id, accounts[1].password);
return 0;
}
and the name_pass.txt file is a simple file like this (name+password):
hello 1234
lol 123
world 123
You are reading file two times. So you need to fseek(), or rewind() to first char before second loop starts.
try with:
fseek(fp, 0, SEEK_SET); // same as rewind()
or
rewind(fp); // s
this code you need to add between two loops (after first and before second loop)
Additionally, you are to allocate memory for id, password filed in account struct:
struct account {
char *id;
char *password;
};
or do allocate memory statically as #Adrián López suggested in his answer.
EDIT I corrected you code:
struct account {
char id[20];
char password[20];
};
static struct account accounts[10];
void read_file(struct account accounts[])
{
FILE *fp;
int i=0; // count how many lines are in the file
int c;
fp=fopen("name_pass.txt", "r");
while(!feof(fp)) {
c=fgetc(fp);
if(c=='\n')
++i;
}
int j=0;
rewind(fp); // Line I added
// read each line and put into accounts
while(j!=i-1) {
fscanf(fp, "%s %s", accounts[j].id, accounts[j].password);
++j;
}
}
int main()
{
read_file(accounts);
// check if it works or not
printf("%s, %s, %s, %s\n",
accounts[0].id, accounts[0].password,
accounts[1].id, accounts[1].password);
return 0;
}
and its working as follows:
:~$ cat name_pass.txt
hello 1234
lol 123
world 123
:~$ ./a.out
hello, 1234, lol, 123
You need to malloc() the content of the pointers in your struct or declaring then with an static size:
struct account {
char id[20];
char password[20];
};
You should probably first allocate memory for the stuff you're scanfing in. Keyword is malloc, a bit too long to lecture right here.