Error Segmentation Fault Core Dumped in C - Ubuntu - c

I am facing this error. I have searched on Internet and that solution is passing two arguments in main, argc and argv. I dont know why to use it and how i use it?
My program is to read a file that contains integers and print them
#include<stdio.h>
int main()
{
int no;
char ch;
FILE *ftr;
ftr = fopen("numbers.txt", "r");
while ((ch = fgetc(ftr)) != EOF)
{
no = ch - '0';
printf("%d", no);
}
fclose(ftr);
return 0;
}

The only explanation for this is that ftr == NULL, try
#include <stdio.h>
int main(void)
{
FILE *file;
char chr;
file = fopen("numbers.txt", "r");
if (file == NULL) {
fprintf(stderr, "cannot open the file\n");
return -1;
}
while ((chr = fgetc(file)) != EOF) {
fprintf(stdout, "%d", chr - '0');
}
fclose(file);
return 0;
}

Ideally you should check file opening and close by using the same level of checking as employed by these two snippets.
f = fopen(filename,"r");
if (f == NULL) {
fprntf(stderr, "fopen failed: %s", strerror(errno));
// and terminate the file IO here
}
..
..
if (fclose(f) == EOF) {
fprint(stderr, "fclose failed");
}

Related

How do I check if every word in a text file is in a dictionary that contains every English word?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char file(FILE *fh, char c[45]);
int lejiko(FILE *lh);
void split(FILE *fh);
int main() {
int choice;
char c[45];
FILE *fh;
FILE *lh;
file(fh, c);
lejiko(lh);
split(fh);
return 0;
}
char file(FILE *fh, char c[45]){
fh = fopen("test.txt", "r");
if (fh != NULL) {
printf("Loaded File");
/* while ((c = fgetc(fh)) != EOF)
putchar(c); */
} else
printf("ERROR");
fclose(fh);
return c;
}
int lejiko(FILE *lh) {
int count = 0;
char t;
lh = fopen("englishWords.txt", "a+");
if (lh != NULL) {
printf("\nLoaded Dictionary");
}
for (t = getc(lh); t != EOF; t = getc(lh))
if (t == '\n')
count = count + 1;
printf("\nYparxoun %d lejeis sto lejiko.\n", count);
return count;
}
void split(FILE *fh) {
char array[45];
char *spl;
fh = fopen("test.txt", "r");
if (fh == NULL)
perror("Error opening file");
else {
while (fgets(array, 45, fh) != NULL) {
printf("%s\n", array);
spl = strtok(array, " ");
while (spl != NULL) {
printf("%s\n", spl);
spl = strtok(NULL, " ");
}
}
fclose(fh);
}
return 0;
}
FILE:I dont know what this is.im.just.testing.out.
Output:
I
dont
know
what
this
is.im.just.testing.out
.
.
This is what I have accomplished so far. I think that the way this will work is by storing every word from the text file and the dictionary in to two matrices and from there by comparing the elements of the matrices.So far i have managed to separate each word whenever there is a space, but when there is punctuation in the text it doesn't seem to work. I have tried multiple ways to remove punctuation from the text, but I cannot get it to work. Also dont mind the functions that just print their names, they will be used for later versions.

How to replace a character in text file using C?

I need to read a text file (E3-5.txt), and search for character c1 to be replaced by c2.
This is my incomplete code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c;
char c1 = 'm';
char c2 = 'a';
int i;
FILE* fp;
fp = fopen("C:\\E3-5.txt", "r+");
if (fp == NULL)
{
printf("File not found!");
return 0;
}
for(c = getc(fp); c != EOF; c = getc(fp))
{
if(c == 'm')
{
i = ftell(fp);
printf("\nPosition %d", i);
}
}
}
I am having trouble how to locate the position of c1 in the text and how to rewrite it.
Edit:
I used the code from the answer, but it didn't change the text.
This is the new code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c;
char c1 = 'm';
char c2 = 'a';
int i;
FILE* fp;
fp = fopen("C:\\E3-5.txt", "rb+");
if (fp == NULL)
{
printf("File not found!");
return 0;
}
else
{
for(c = getc(fp); c != EOF; c = fgetc(fp))
{
if(c == c1)
{
fseek(fp, -1, SEEK_CUR);
fputc(c2, fp);
}
else
{
return 0;
}
}
}
return 0;
}
The program returned 0 without writing anything in the text
Here you have a very naive one:
int freplace(FILE *f, char needle, char repl)
{
int result = 1;
int c;
if(f)
{
while((c = fgetc(f)) != EOF)
{
if(c == needle)
{
fseek(f, -1, SEEK_CUR);
fputc(repl, f);
//all I/O functions require error handling
}
}
}
return result;
}
getc() returns an int so you need to declare int c not char c to check for the EOF.
ftell() gets the location. Use fwrite() or fputc() to write to file at that location by setting with fseek().
Go to https://en.cppreference.com/w/c for reference. Lots of beginners fail to read all of the standard library functions, and some even reinvent the wheel.
You really don't want to directly manipulate a file. Ever. Doing so is just asking for data corruption. Instead, create a new file and move it when you're done. Also, it's a lot easier to write the code. You can do so with something like:
#include <stdio.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
int c1 = argc > 1 ? argv[1][0] : 'm';
int c2 = argc > 2 ? argv[2][0] : 'a';
const char *path = argc > 3 ? argv[3] : "stdin";
FILE *in = argc > 3 ? fopen(path, "r") : stdin;
if( in == NULL ){
perror(path);
return 1;
}
FILE *out = stdout;
char tmp[1024] = ".tmpXXXXX";
char *outpath = "stdout";
if( argc > 3 ){
outpath = tmp;
int fd = mkstemp(tmp);
if( fd == -1 ){
perror("mkstemp");
return 1;
}
if( (out = fdopen(fd, "w")) == NULL ){
perror(tmp);
return 1;
}
}
int c;
while( (c = fgetc(in)) != EOF ){
if( c == c1 ){
c = c2;
}
if( fputc(c, out) == EOF ){
perror(outpath);
return 1;
}
}
if( argc > 3 ){
if( fclose(out) ){
perror(outpath);
return 1;
}
if( rename(outpath, path) ){
perror(path);
return 1;
}
}
return 0;
}
String replace
Just for completeness, here is a bit of code to replace a word in a file! This will replace a single character, so of course it answers the question and shows some useful examples.
This is also my first and only non-trivial golden program, written in May 1994! Although you can certainly find fault with it, it worked as intended and my co-workers and I used it many different ways for sysadmin-related tasks. Compiled on MS C/C++
#include <stdio.h>
#include <string.h>
#define err(e) {_fcloseall(); fprintf(stderr, \
"USAGE: chg source dest oldstr newstr\n%s\n",e); exit(1);}
main (int argc,char *argv[])
{
FILE *in,*out;
char buffer[200];
char *old,*new;
int i,j,k;
if (argc!=5)
err("invalid # of parameters");
if ((in=fopen(argv[1],"r"))==NULL)
err("Can't open source");
if ((out=fopen(argv[2],"w"))==NULL)
err("Can't open dest");
old=argv[3];
new=argv[4];
if (*old=='"')
old++;
if (*new=='"')
new++;
if (i=strlen(old) && old[i-1]=='"')
old[i-1]=0;
if (i=strlen(new) && new[i-1]=='"')
new[i-1]=0;
if (!*old)
err("Can't search for nothing!");
if (!*new)
err("Can't replace nothing!");
j=0;
while (!feof(in))
{
if ((buffer[j]=fgetc(in))==EOF)
break;
buffer[j+1]=0;
j++;
if (!old[j-1])
{
fprintf(out,new);
fputc(buffer[j-1],out);
j=0;
}
else if (_strnicmp(buffer,old,j))
{
fprintf(out,buffer);
j=0;
}
else if (j>195)
err("Internal error, buffer filled past 195");
}
}

Basic File IO in C Produces all a's

I am using CodeBlocks on Windows to compile.
Why the program gives me this answer? Why there are so much as and don't get the answer 123456abcdef?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
char s[100] = "abcdef";
char c1 = '0';
int i = 0;
fp = fopen("ot.txt", "w");
if (fp == NULL) {
printf("file open error");
exit(0);
}
while (s[i] != '\0') {
fputc(s[i], fp);
i++;
printf("%d", i);
}
while (c1 != EOF) {
c1 = fgetc(fp);
putchar(c1);
}
fclose(fp);
}
There are multiple problems in your code:
c1 should be defined with type int to accommodate for all values returned by fgetc(). a char cannot unambiguously store EOF.
You should open the file in write+update mode "w+"
You should rewind the stream pointer before reading back from it for 2 reasons: a seek operation is required between read and write operations and you want to read the characters from the start of the file.
You need to test for EOF after reading a byte with fgetc(), otherwise you will output the EOF converted to unsigned char to stdout before exiting the loop.
It is good style to return 0; from main() to indicate success and non-zero to indicate failure.
Here is a corrected version:
#include <stdio.h>
int main(void) {
FILE *fp;
char s[] = "abcdef";
int i, c;
fp = fopen("ot.txt", "w+");
if (fp == NULL) {
printf("file open error\n");
return 1;
}
i = 0;
while (s[i] != '\0') {
fputc(s[i], fp);
i++;
printf("%d", i);
}
rewind(fp);
while ((c1 = fgetc(fp)) != EOF) {
putchar(c1);
}
printf("\n");
fclose(fp);
return 0;
}

Issues in string manipulation

The log.txt file consist of some data. The program looks for ":" and when it find it prints "Done". The program compiles successfully but never prints "Done".
char *atrbt ;
FILE *fp;
int i = 0;
if (fp = fopen("log.txt", "r+")) {
while (fscanf(fp, "%c", &atrbt) != EOF) {
printf("%c", atrbt);
if(atrbt[i] == ':') { <------------ Issue
printf("Done");
}
++i;
}
}
You are mixing between char and char pointers. One of the possible correct ways could be (code is untested):
char atrbt;
FILE *fp;
if (fp = fopen("log.txt", "r+")) {
while ((atrbt = getc(fp)) != EOF) {
printf("%c", atrbt);
if(atrbt == ':') {
printf("Done");
}
}
}

C read/write to file - Access Violation

I am trying to read and write simple Infix and Postfix expressions to a from a file. When the program reaches the lines where fgets is called, an Access Violation error pops up.
Code:
#include <stdio.h>
#include <stdlib.h>
#include "header3.h"
char inFx[100], postFx[100];
int main() {
FILE *fp = fopen_s(&fp, "input.txt", "r");
remove("output.txt");
FILE *fp2 = fopen_s(&fp2, "output.txt", "a");
if (fp == 0)
{
printf("Could not open file\n");
}
else
{
int i = 0;
while (fgets(inFx, sizeof(inFx), fp)) { //access violation during runtime here
size_t ln = strlen(inFx);
int n = expEvaluate(inFx, ln, postFx); //refers to other class
if (inFx[ln] == '\n')
inFx[ln] = '\0';
if (fp2 == 0)
{
printf("Could not open file\n");
}
else
{
while (*(postFx + i) != 0)
{
fputc(*(postFx + i++), fp2);
}
fputc('\n', fp2);
}
}
}
fclose(fp2);
fclose(fp);
return 0;
}
fopen_s() returns an error code, NOT the file handle (that is assigned to the first parameter).
You should not get the result of fopen_s into your FILE pointers.
Also, you should put your test on fp2 before your loop. If you cannot open the File, then you will read your whole file fp but you won't do anything.

Resources