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]);
}
Related
I am trying to make a program that reads numbers from a text file named numbers.txt that contains different numbers in each line.
For example:
8321
12
423
0
...
I have created this program, but it does not work properly. I have tried many things and don't know what to do. Can someone guide me in the right direction? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1000
int main(int argc, char *argv[]) {
char str[MAX_LEN];
FILE *pFile = fopen(argv[1], "r");
int num;
int sum = 0;
int count = 0;
if (pFile == NULL) {
printf("Error opening file.\n");
return 1;
}
while (!feof(pFile) && !ferror(pFile)) {
if (fscanf(pFile, "%d", &num) == 1) {
count++;
while (strcmp(fgets(str, MAX_LEN, pFile), "\0") == 0) {
printf("%s", str);
//sum = sum + (int)(fgets(str, MAX_LEN, pFile));
printf("\n");
}
}
}
fclose(pFile);
printf("count = %d \n", count);
printf("sum = %d \n", sum);
return 0;
}
strcmp(fgets(str, MAX_LEN, pFile),"\0") is wrong in many ways. For one, the argument of strcmp must be a string (which a null pointer isn't), but fgets returns NULL on error or end of file. You need to check that it didn't return NULL and then you can compare the string in str. However, there is no need to strcmp against "\0" (or, in this case equivalently, "") to detect the end of file, because that's when fgets returns NULL.
Another issue is that you are reading with both fscanf and fgets – pick one and stick with it. I recommend fgets since it's generally easier to get right (e.g., on invalid input it's a lot harder to recover from fscanf and make sure you don't get stuck in an infinite loop while also not losing any input). Of course you need to parse the integer from str after fgets, though, but there are many standard functions for that (e.g., strtol, atoi, sscanf).
Don't use !feof(file) as the loop condition (see, e.g., Why is “while ( !feof (file) )” always wrong?). If you are reading with fgets, end the loop when it returns NULL.
You can use strtok to split the numbers in each line, then using atoi function to convert string to int.
For example:
while(fgets(str, MAX_LEN, pFile)) {
// if the numbers are separated by space character
char *token = strtok(str, " ");
while(token != NULL) {
sum += atoi(token);
strtok(NULL, " ");
}
}
if there is only one number per line, you do not need to use strtok:
while(fgets(str, MAX_LEN, pFile)) {
sum += atoi(str);
// OR
sscanf(str,"%d\n", &new_number)
sum += new_number;
}
Your program has multiple problems:
no test if a command line argument was passed.
while (!feof(pFile) && !ferror(pFile)) is always wrong to iterate through the file: feof() gives valid information only after a actual read attempt. Just test if the read failed.
if fscanf(pFile, "%d", &num) == 1) add the number instead of just counting the numbers.
strcmp(fgets(str, MAX_LEN, pFile), "\0") will fail at the end of the file, when fgets() returns NULL.
If the file only contains numbers, just read these numbers with fscanf() and add them as you progress through the file.
Here is a modified version:
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *pFile;
int num
int sum = 0;
int count = 0;
if (argc < 2) {
printf("Missing filename\n");
return 1;
}
if ((pFile = fopen(argv[1], "r")) == NULL) {
printf("Error opening file %s\n", argv[1]);
return 1;
}
while (fscanf(pFile, "%d", &num) == 1) {
sum += num;
count++;
}
fclose(pFile);
printf("count = %d \n", count);
printf("sum = %d \n", sum);
return 0;
}
Absolutely new to C. I am trying to write a program to either read integers contained in a file (passed as arg) or from stdin. First number read is supposed to indicate the array size.
I have something but it throws segmentation fault. Please help.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]) {
FILE *f;
int n, numbers[n], firstNum;
if (argc != 0)
{
f = fopen(argv[1], "r");
fscanf(f, "%d", & firstNum);
int numbersArray[firstNum];
for (int i = 0; i < firstNum; i++)
{
fscanf(f, "%d", &numbersArray[i]);
}
for (int i = firstNum; 0 <= i; i--)
{
printf("Numbers: %d\n\n", numbersArray[i]);
}
fclose(f);
}
else
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
fscanf(stdin, "%d", &numbers[i]);
printf("%d\n", i, numbers[i]);
}
return 0;
}
First off always initialize your variables like kaylum and myself mentioned in the comments.
Unlike some other programming languages C doesn't initialize your variables for you.
Now for the question you posted, you got the idea mostly correct but there are things that i suggest you change:
int n, numbers[n], firstNum;
to
int n = 0, numbers[1000], firstNum = 0;
If you're not happy with that you could move the numbers[n] lower when n is initialized but i wouldn't advise that.
Instead of that, since you're learning C have a look at dynamically allocated arrays using pointers.
Some links to help you understand pointers:
https://www.cprogramming.com/tutorial/c/lesson6.html
https://www.tutorialspoint.com/cprogramming/c_pointers.htm
Next have a look at your fopen it has a return value that tells you if it succeeded to open the file you requested.
So you can add:
f = fopen(argv[1], "r");
if (f == NULL)
{
printf("File Not Found!");
return -1;
}
Modify the condition to suite the way you want to handle that error.
When you're reading the file the user specifies the size of the array you're reading but you should consider the fact that the file may not contain the exact amount of elements.
The function that you are using fscanf has a way to tell you that and that's it's return value.
It will return EOF which is a special value that translates to End Of File.
Consider modifying your fscanf to this:
if (fscanf(f, "%d", &firstNum) == EOF)
{
printf("ERROR");
}
Or if you're in a for loop put break
The last thing is that you don't have to explicitly use fscanf for stdin, the user has specified that he will input it through stdin so you can just as well use scanf.
Hope this helps and good luck with your future C endeavors.
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.
Originally, this function was embedded into the main function, creating a very cluttered main function. The program replaces tabs with the number of spaces. I'm still confused as to what goes inside the argument lists for my functions and how to pass argc/argv from main into these functions. Did I do this right?
There are some defined variables at the top of the file:
#define OUTFILE_NAME "detabbed"
#define TAB_STOP_SIZE 8
#define NUM_ARGS 2
#define FILE_ARG_IDX 1
Here's my second attempt at it:
void open_file(FILE *inf, FILE *outf, char *in[]) /*I feel like the arguments aren't right
{ and this function is just opening
and reading files*/
inf = fopen(in[1], "r");
outf = fopen(OUTFILE_NAME, "w");
if (inf == NULL)
{
perror(in[1]);
exit(1);
}
else if (outf == NULL)
{
perror(OUTFILE_NAME);
exit(1);
}
fclose(inf);
fclose(outf);
}
void detab(FILE *infile, FILE *outfile, char *argument[]) /* Confused about argument list
{ and this function actually
char c; does the detabbing */
int character_count = 0, i, num_spaces;
open_file(infile, outfile, argument); /* I want to call the previous
function but again, confused
while (fscanf(infile, "%c", &c) != EOF) about the argument list */
{
if (c == '\t')
{
num_spaces = TAB_STOP_SIZE - (character_count % TAB_STOP_SIZE);
for (i = 0; i < num_spaces; i++)
{
fprintf(outfile, " ");
}
character_count += num_spaces;
}
else if (c == '\n')
{
fprintf(outfile, "\n");
character_count = 0;
}
else
{
fprintf(outfile, "%c", c);
character_count++;
}
}
}
int main(int argc, char *argv[])
{
if (argc < 1)
{
fprintf(stderr, "usage: prog file\n");
exit(1);
}
else if (argc < NUM_ARGS)
{
fprintf(stderr, "usage: %s file\n", argv[0]);
exit(1);
}
detab(argc, argv); /* I want to pass argc and argv to the detab function, but I'm
having trouble with the argument list */
return 0;
}
What I need help with, is figuring out what goes in the argument lists of the functions. I think what confuses me is how to get my argument types to match, so that I can pass variables from one function to the other.
Decomposition is not your biggest problem here. Rather careless error checking, the use of old overweighted fscanf() and fprintf() and global variables are. Furthermore, the lack of const correctness in the input filenames, the overly long and verbose variable names and your unawareness of the += and ++ operators are just the bonus. I suppose that's why your code looks like it's bloated (and it is, in fact).
I'd rewrite the function like this:
void detab(const char *in, const char *out, int tabstop)
{
FILE *inf = fopen(in, "r");
if (!inf) return;
FILE *outf = fopen(out, "w");
if (!outf) {
fclose(inf);
return;
}
int n = 0;
int c;
while ((c = fgetc(inf)) != EOF) {
if (c == '\t') {
int pad = tabstop - n % tabstop;
for (int i = 0; i < pad; i++)
fputc(' ', outf);
n += pad;
} else if (c == '\n') {
fputc('\n', outf);
n = 0;
} else {
fputc(c, outf);
n++;
}
}
fclose(inf);
fclose(outf);
}
If you want to decompose this even further, then you may write a function taking two FILE * and the tab stop as its arguments and it shall contain the while loop only - doing that is left to you as an exercise.
Note: This answer was given to an earlier edit of the question. It has changed in the meantime, so this answer may no longer seem relevant.
Coming from an OOP background, I will focus on one single issue that is there known as Single Responsibility Principle (SRP). I argue that detab (and every other function) should do only one specific thing, but do that thing well.
But it doesn't just "detab", as its name suggests; it also has to extract its actual arguments from the command-line variables argc and argv, which were forced upon it by main:
detab(argc, argv);
main has done some validation before that, but because the command-line is then simply passed to the function, you obviously felt like continuing validation in detab (I also make some additional remarks about violating the SRP below):
void detab(int arg_list, char *array[]) // why ask for arg_list if you don't need it?
{
…
infile = fopen(array[1], "r"); // not obvious to caller that only array[1] is relevant
…
if (infile == NULL)
{
perror(array[1]);
exit(1); // should your function really have the power to terminate the program?
}
…
}
It would seem much more reasonable to concentrate all the command-line validation and value extraction logic in one place, and the detabbing in another; that is, draw clear boundaries of responsibility. Don't let logic of one function spill over into another!
To me, detab's signature should look more like e.g. this:
void detab(FILE *in, FILE *out);
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...