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");
}
Related
I would like to do two Things in my code
1)Write a program to write a two dimensional integer array to a text file.
and
2)Write a second program to read a two dimensional integer array from a text file. The second program should print the matrix on screen. Also to get the filename I should use command line argument.
For example on the cmd the output should be like this:
matrix.txt
8 3 3 1
13 5 31 -8
9 9 0 42
And this is the code which I have made. However only the error message "Can't open matrix.txt" comes out. What is the problem with my code?
#include <stdio.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
#define ROW 3
#define COL 4
#define FILE_NAME "matrix.txt"
void input_matrix(int matrix[ROW][COL], FILE*);
int main()
{
int Multiarray[ROW][COL];
int i, j;
FILE* fp;
fp = fopen_s(&fp, FILE_NAME, "r");
if (fp == NULL)
{
fprintf(stderr, "Can't open %s\n", FILE_NAME);
exit(EXIT_FAILURE);
}
else
{
input_matrix(Multiarray, fp);
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
fprintf(fp, "%d ", Multiarray[i][j]);
}
fprintf(fp, "\n");
}
}
//This part should print out the result of my input
close(fp);
return 0;
}
void input_matrix(int matrix[ROW][COL], FILE* fp)
{
int i, j;
fp = fopen_s(&fp, FILE_NAME, "w");
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
fscanf_s(fp, "%d", &matrix[i][j]);
// I have already scanned all the element of my array
}
}
}
Function fopen_s returns 0 on success. As result the program fails on success.
Try:
int ret = fopen_s(&fp, FILE_NAME, "r");
if (ret != 0)
{
fprintf(stderr, "Can't open %s\n", FILE_NAME);
exit(EXIT_FAILURE);
}
I want to read the matrix from file and store it in an array. But the array is storing only the last value of matrix. Can anyone explain this please?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp, *fp1;
int n = 0, i, j, a[4][4], b[16];
fp = fopen("Output.txt", "r");
if (fp == NULL) {
printf("\nError; Cannot open file");
exit(1);
}
while (!feof(fp)) {
i = 0;
fscanf(fp, "%d", &n);//reads the file containing matrix
b[i] = n;//this part is not working
printf("%d\n", n);
i++;
}
fclose(fp);
fp1 = fopen("Output2.txt", "w");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
fprintf(fp1, "%d\t", a[i][j] * 2);
}
fprintf(fp1, "\n");//creates file of altered matrix
}
fclose(fp1);
return 0;
}
Your input loop is incorrect:
you reset i to 0 at the beginning of each iteration
you use an incorrect test: while (!feof(fp)). Learn here why: Why is “while ( !feof (file) )” always wrong? . You should instead test the array index against the array length and check if fscanf() succeeds at reading the next value.
Here is a corrected version:
for (i = 0; i < 16; i++) {
if (fscanf(fp,"%d",&n) != 1) { //reads the file containing matrix
fprintf(stderr, "invalid input\n");
exit(1);
}
b[i] = n;
printf("%d\n", n);
}
Note also that you do not read the values into the 2D matrix, so the output loop has undefined behavior because a is uninitialized.
Here is a improved version:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
int i, j, a[4][4];
fp = fopen("Output.txt", "r");
if (fp == NULL) {
fprintf(stderr, "Error: Cannot open file Output.txt for reading\n");
exit(1);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (fscanf(fp, "%d", &a[i][j]) != 1) {
fprintf(stderr, "invalid input for a[%d][%d]\n", i, j);
fclose(fp);
exit(1);
}
}
}
fclose(fp);
fp1 = fopen("Output2.txt", "w");
if (fp1 == NULL) {
fprintf(stderr, "Error: Cannot open file Output2.txt for writing\n");
exit(1);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
fprintf(fp1, "%d\t", a[i][j] * 2);
}
fprintf(fp1, "\n");
}
fclose(fp1);
return 0;
}
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
I am new to C programming and I have been trying to make a simple program that reads integers from a .txt file into an array then print it.
The numbers in the file are arranged as follows:
23
44
12
41
123
And this is the code I have been trying:
void main()
{
FILE *fp;
int num[100],i,j;
fopen_s(&fp, "C:/Users/User1/Desktop/NUI/fp.txt", "r");
if (fp == NULL)
{
printf("Can't open file for reading.\n");
}
else
{
for (i = 0; i<5; i = i + 1) {
fscanf_s(fp, "%d", &num[i]);
}
}
for (j = 0; j<5 ; j = j + 1) {
printf("%d\n", num[j]);
}
fclose(fp);
}
In the FOR LOOP I have to write i<5 , j<5 to set number of iterations.But I want to know of there is a way to make the loop recognise the final number automatically.
(Something similar to char[i]!='\0' but for int array)
You can use EOF that means end of file.
In this sample I read the file intFile.txt and print the numbers that I have read.
#include <stdio.h>
int main()
{
FILE * fp;
int numInt[100];
int counter = 0;
fp = fopen ("intFile.txt", "r");
while(fscanf(fp, "%d", &numInt[counter])!= EOF)
{
printf("num = %d\n",numInt[counter++]);
}
fclose(fp);
return 0;
}
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");
}