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.
Related
I'm a beginner in data structures with C, I have taken C programming but I've only touched a little bit on structures in the course and I have not kept up with it.
Anyways, I'm trying to make a program that will read data into an array of structures from a file and print out the contents of the array you have populated. I need help figuring this out.. I'm honestly not too sure if I'm doing this correctly either... :/
Any help is greatly appreciated, and thank you in advance! :)
This is what I tried so far
Here's my code:
FYI - The file I'm trying to open is DataFile.txt
#include<stdio.h>
#include <stdlib.h>
#define SIZE 10
#define ARRAY_SIZE 30
//Struct contains 3 fields, name, age, salary
typedef struct
{
char name[SIZE];
int age;
int salary;
} data;
data a[ARRAY_SIZE];
FILE * fp = fopen("DataFile.txt", "r");
if (fp == NULL)
{
printf("Error %s.\n", strerror(errno));
exit(1);
}
int GetData()
{
int i = 0;
fscanf(fp, "%s", a[i].name);
while(fp && i<ARRAY_SIZE)
{
fscanf(fp, "%d", &a[i].age);
fscanf(fp, "%d", &a[i].salary);
i++;
}
return i;
}
void ShowData( int records_read)
{
//Print text file data on screen
for(int i=0;i<records_read;i++)
{
printf("%s %d %d\n", a[i].name, a[i].age, a[i].salary);
}
}
int main()
{
char name[256];
int i = 0;
int records_read;
//Call the method, getData
i = GetData();
//Prompt and read input from the user
printf("Pick a number from 1 to 10:");
scanf("%d", &records_read);
//Call the method, showData
ShowData(records_read);
fclose(fp);
return 0;
}
The program works if I don't put this part of the code in:
FILE * fp = fopen("DataFile.txt", "r");
if (fp == NULL)
{
printf("Error %s.\n", strerror(errno));
exit(1);
}
BUT the output is just a list of zeros..
A quick answer: At first, try to split FILE * fp = fopen("DataFile.txt", "r"); into two parts as one is the variable declaration FILE * fp = NULL; and the other one is the assignment expression fp = fopen("DataFile.txt", "r");. And then keeps the part of the variable declaration out of all the functions, while moves both the part of the assignment and the if-statement if (fp == NULL){...} into function GetData(). The code might work in this case.
When I compile the program and run it, it does not print anything. I believe the problem is on the while but I can't understand what is wrong. It is supposed to convert hex to ASCII and then the encrypted message.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(int argc, char **argv) {
int p;
//Opening a file
FILE*tp;
tp = fopen(argv[1], "r");
if(tp == NULL)
{
printf("Error opening file!\n");
return 0;
}
else
{
//Decryption code
while((p=fscanf(" %x",&p))!=EOF)
{
p=p >> 2;
p=p - 200;
printf(" %c",p);
}
}
return 1;
fclose(tp);
}
fscanf() returns number of input items successfully matched and assigned, not input items themselves. Also, as mentioned above, you need to pass file pointer to the function. Try this: while(fscanf(tp, "%x", &p) != EOF)
Looks like you need to specify and provide the FILE pointer "tp" to the fscanf function.
I'm trying to make a program in c90 which will read some words from a txt file and copy them to a matrix array. It seems that the compilation is all right but there is a thread named "EXC_BAD_ACCESS(code=1 adress=0x68). can you help me figure out where the problem is??
int main(int argc, char *argv[]) {
FILE *input;
char words[10][30];
int i,a;
input=fopen("test.txt","rt");
for(i=0;i<10;i++){
a = fscanf(input,"%s", words[i]);
printf("%2d %s\n", a, words[i]);
}
fclose(input);
return 0;
}
Check that your file is actually being opened, otherwise printf() will try to print out random memory which may go beyond the bounds of what you have actually allocated and cause an error.
input = fopen("test.txt", "rt");
if (!input)
{
perror("Failed to open file");
exit(1);
}
You may also want to check that a == 1, i.e. that the fscanf() also succeeds.
I am getting segmentation fault when i compile my code.
I am not getting what is wrong with my code will be happy if someone can help me.
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
FILE *fp;
char fline[100];
char *newline;
int i,count=0,occ=0;
fp=fopen(argv[1],"r");
while(fgets(fline,100,fp)!=NULL)
{
count++;
if(newline=strchr(fline,'\n'))
*newline='\0';
if(strstr(fline,argv[2])!=NULL)
{
printf("%s %d %s",argv[1],count,fline);
occ++;
}
}
printf("\n Occurence= %d",occ);
return 1;
}
See man open and man fopen:
FILE *fp;
...
fp=open(argv[1],"r");
open returns an integer, not a file pointer. Just change that line to
fp=fopen(argv[1],"r");
Note: OP edited this error out of the code in the question, for those who wonder what this is about
Which leads us to (some other minor issues addressed as well - see comments):
+EDIT: point to places where error checking should be done:
#include<stdio.h>
#include<string.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *fp;
char fline[100];
char *newline;
int i, count = 0, occ = 0;
// for starters, ensure that enough arguments were passed:
if (argc < 3) {
printf("Not enough command line parameters given!\n");
return 3;
}
fp = fopen(argv[1], "r");
// fopen will return if something goes wrong. In that case errno will
// contain the error code describing the problem (could be used with
// strerror to produce a user friendly error message
if (fp == NULL) {
printf("File could not be opened, found or whatever, errno is %d\n",errno);
return 3;
}
while (fgets(fline, 100, fp) != NULL) {
count++;
if (newline = strchr(fline, '\n'))
*newline = '\0';
if (strstr(fline, argv[2]) != NULL) {
// you probably want each found line on a separate line,
// so I added \n
printf("%s %d %s\n", argv[1], count, fline);
occ++;
}
}
// it's good practice to end your last print in \n
// that way at least your command prompt stars in the left column
printf("\n Occurence= %d", occ);
return 1;
}
ps: so the error occurs during runtime and not during compile time - this distinction is quite crucial, because hunting down a compiler failure and solving a library usage error require rather different techniques...
I'm working on a Computer Programming assignment to read in lines from a file and determine if it is a(n):
impure palindrome: Ignores punctuation and case
for example: Madam I'm Adam is an impure palindrome.
pure palindrome: checks punctuation and case
e.g. evil rats on no star live is a pure palindrome.
I have created functions for both of these cases and they work fine.
My problem lies with opening files
I have a function that reads in a filename from the argv[] and it's mean to calculate the number of impure/pure palindromes and the number of lines. And it also kinda works BUT!!
When I check the output with the printf functions I've put in I believe the address of the file is included in when gets is used. Other than that It works fine. My code also works when I hardcode a filename into it. I think it has something to do with pointers and memory addresses but I'm stumped.
I have read a similar question to this but the answer wasn't provided since the op was able to solve it.
Here is the link: Opening a file inside a function using fopen
I didn't think it was necessary to include my pure palindrome and impure palindrome functions for this question. If I'm wrong I am happy to include them.
My read file function:
void read_file(const char* filename)
{
bool impure = false;
bool pure = false;
int purecount = 0;
int impurecount = 0;
int linecount = 0;
FILE *file = fopen(filename, "r");
if (file != NULL)
{
char line[FILE_LEN];
char line1[FILE_LEN];
while (fgets(line, sizeof line, file) != NULL)
{
printf("%s\n", line);
sscanf(line, "%[^\n]", line1);
pure = is_a_pure_palindrome(line1);
impure = is_an_impure_palindrome(line1);
printf("%s\n", line);
if (pure == true)
purecount++;
else if (impure == true)
impurecount++;
linecount++;
}
fclose(file);
printf("There are %d pure palindromes and %d impure palindromes and %d lines\n", purecount, impurecount, linecount);
}
else
{
perror("fopen");
}
return;
}
My main function:
int main(int argc, char *argv[])
{
int i = 0;
for (;i< argc; i++)
{
read_file( argv[i]);
}
return EXIT_SUCCESS;
}
argv[0] represents program execution path name.
Arguments in C/C++ start from 1.
Change to:
int i = 1;
for (;i< argc; i++)
{
read_file( argv[i]);
}