fscanf not reading from a file containing asterisk characters - c

I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}

I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution

Related

Thread 1: EXC_BAD_ACCESS (code=1, address=0x68 [duplicate]

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

C program to put the output into a new file

So i have een solving a problem where i have to find the prime numbers from the input file and save those prime numbers in an output file called output.txt.But If there are no prime numbers in the input file, i'll have to write “No prime numbers found” in the output file.So when i completed the code when there is no prime number it shows No prime numbers found 5-6 times and i only want it to appear 1 time.What is my mistake here?I am totally a noob here
#include <stdio.h>
#include <stdlib.h>
int Primecheck(const int number);
int main()
{
FILE* Number,
* Prime_N;
int num;
char sentence[50] = "No prime numbers found";
int length = strlen(sentence);
int i;
Number = fopen("input.txt", "r");
Prime_N = fopen("output.txt", "w");
if (Number == NULL || Prime_N == NULL)
{
printf("Unable to open file.\n");
exit(EXIT_FAILURE);
}
printf("File opened and Reading Done \n\n");
while (fscanf(Number, "%d", &num) != -1)
{
if (Primecheck(num) == 1)
fprintf(Prime_N, "%d\n", num);
else
for (i = 0; i < length; i++)
{
fputc(sentence[i], Prime_N);
}
}
fclose(Number);
fclose(Prime_N);
printf("Overwrite Success.");
return 0;
}
int Primecheck(const int number)
{
int i;
if (number < 0)
return 0;
for (i = 2; i <= number / 2; i++)
{
if (number % i == 0)
{
return 0;
}
}
return 1;
}
instead of
else
for(i=0;i<length;i++)
{
fputc(sentence[i] ,Prime_N);
}
you can just write
else
printf("No prime numbers found");
Well , as I see from your code , each time you read a number from the file you check if prime write it or write sentence . so of course you get multiple output ,
you should write the number to char* then check if changed after reading from Number and checking if prime write the number in the char* after the loop just check if the length of the char* that you stored the primes in it if changed write it else write your sentence ... Done
something like this
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef struct {
char* data;
size_t size;
size_t capacity;
} string;
void init_string(string* s, size_t size){
s->data = (char*)malloc(sizeof(char) * size);
s->capacity = size;
s->size = 0;
}
void append(string* s,const char* str){
if(s->capacity - s->size < strlen(str)){
s->data = (char*)realloc(s->data, sizeof(char)* 4 * strlen(str));
}strcat(s->data, str);
}
void free_string(string* s){
free(s->data);
}
int is_odd(int n){
return n%2;
}
int main(){
int num[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
string str;
init_string(&str,1);
char* snum;
for(int i=0; i<18; i++){
if(!is_odd(i)){
sprintf(snum,"%d",num[i]);
append(&str, snum);
append(&str, "\n");
}
//printf(snum);
//strcat(str, snum);
}
printf("%s",str.data);
free_string(&str);
//printf(str);
return 0;
}

Reading the result of a contest from a file and sort the name alphabetically with related score

i have to read from a file which contains names and scores the results of a contest but the function fscanf is not working properly.. Does it have to do with newlines or something?
I'll leave below the code and the screenshots of the issue i'm having.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct contest
{
char name[25];
int score;
}Contest;
int main(int argc, const char * argv[]) {
Contest players[100];
FILE *fp;
fp = fopen("contest.txt", "r");
if(fp == NULL)
{
fprintf(stderr, "Error: failed to open the file\n");
exit(EXIT_FAILURE);
}
int cnt = 0;
while(fscanf(fp, "%s %d", players[cnt].name, &players[cnt].score) != EOF)
{
++cnt;
}
char temp[25];
for(int t = 0; t < cnt; ++t)
{
for(int u = 0; u < cnt; ++u)
{
if(strcasecmp(players[t].name, players[u].name) > 0)
{
strcpy(temp, players[t].name);
strcpy(players[t].name, players[u].name);
strcpy(players[u].name, temp);
}
}
}
for(int t = 0; t < cnt; ++t)
{
fprintf(stdout, "Name : %s Score : %d\n", players[t].name, players[t].score);
}
fclose(fp);
return 0;
}
Input:
Randal  34
Leonel  67
Vaughn  100
Missy  68
Cristopher  92
Dagmar  102
Blondell  88
Milly  83
Darrel  12
Josh  71
Output:
You've just made two little mistakes: (1) forgot to also swap the scores and (2) did the wrong comparison in the strcasecmp. For the rest, it's all working fine here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct contest
{
char name[32];
int score;
} Contest;
int main()
{
Contest players[100];
FILE *fp = fopen("contest.txt", "r");
assert(fp);
int cnt = 0;
while(fscanf(fp, "%s %d", players[cnt].name, &players[cnt].score) != EOF)
++cnt;
for(int i = 0; i < cnt; ++i)
{
for(int j = 0; j < cnt; ++j)
{
if(strcasecmp(players[i].name, players[j].name) < 0)
{
int tempScore = players[i].score;
players[i].score = players[j].score;
players[j].score = tempScore;
char tempName[32];
strcpy(tempName, players[i].name);
strcpy(players[i].name, players[j].name);
strcpy(players[j].name, tempName);
}
}
}
for(int i = 0; i < cnt; ++i)
fprintf(stdout, "Name : %s Score : %d\n", players[i].name, players[i].score);
fclose(fp);
return 0;
}

Getting segmentation fault when using fgets and strtok

I am trying to read a txt file and then split the numbers and store them in a matrix. However when I try to use strtok I'm getting segmentation fault. Can somebody help me with this please!
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void parse(char*file1)
{
FILE *fp;
char str[60];
char str1[60];
fp = fopen(file1, "r");
int row;
int col;
fgets(str, 60, fp);
row=atof(str);
fgets(str, 60, fp);
col=atof(str);
double *matrix;
matrix = (double *)malloc(sizeof(double)*row*col);
int j;
int i;
for(i=0; i < row; i++) {
for(j=0; j < col; j++) {
matrix[i*col +j] = 1;
}
}
for(i=0; i < row; i++) {
for(j=0; j < col; j++) {
printf("%f ",matrix[i*col +j]);
}
printf("\n");
}
printf("**************************");
double dtoken;
while (!feof(fp))
{
if (fgets(str, 60, fp)==NULL)
{
break;
}
else
{
char*token;
token = strtok(str, " ");
while (token!=NULL)
{
printf("%s ",token);
token=strtok(NULL, " ");
}
}
printf("\n");
}
fclose(fp);
}
int main(int argc, char*argv[])
{
int i;
char*file1;
char*file2;
if (argc==1) //print error when no txt file is entered
{
printf("Invalid text file.\n");
exit(1);
}
else if (argc==2)
{
file1=argv[1];
file2=argv[1];
}
else if (argc==3)
{
file1=argv[1];
file2=argv[2];
}
else
{
exit(1);//more than 3 files, invalid
}
//
parse(file1);
}
I tried copying str to str1 and use strtok on str1 and that did not work either.
In the function parse() change str1[60]='\0'; to str1[59]='\0';
As you have allocated memory only for 60 characters and trying to access the 61st character.
In arrays you need to count from 0 to 59 and not from 1 to 60 if the size of allocated array is 60.
EDIT:
Check for the return value of fopen
After fp = fopen(file1, "r"); add below code
if (fp == NULL ) {
printf("Error: Unable to open file\n");
return ;
}
You are causing undefined behavior by accessing str1 out of bounds. You can replace the lines:
strncpy(str1,str,60);
str1[60]='\0';
by
strcpy(str1,str);
That will work fine since both str and str1 are arrays with 60 elements.

Error when trying to read in numbers from txt file in C

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}

Resources