Reading matrices separated by a newline from file - c

I need to read two matrices of any dimension from a file in this format:
1 2 4
1 3 7
9 2 4
0 2 4
1 5 7
0 2 4
The second matrix mustn't necessarily be present. I wrote a code that can already read the first matrix:
int main (int argc, char *argv[]){
FILE *fp;
int i, j;
int initial_dim = 5;
int n1 = 0; /*dimension of the first matrix*/
int n2 = 0; /*dimension of the second matrix*/
double A[n][n];
double B[n][n];
if (argc == 1){
printf("Please enter file name\n");
return 1;
}
if( (fp = fopen(argv[1], "r")) != NULL ){
for(i=0; i < initial_dim; i++)
for(j=0; j < initial_dim; j++)
if (fscanf(fp, "%lf", &A[i][j]))
n1++;
double x = determinant(n1, A);
printf("Determinant: %g\n", x);
fclose(fp);
}
else{
printf("I can't open file %s\n", *argv);
return 1;
}
return 0;
}
I need a way to skip the delimiter and read the second matrix

I could not find a way to write a short answer so I just wrote the code that would do this here: http://gitlab.dotty.fr/dotty/read_matrix/tree/master
The code I wrote can read as many matrices as you want from an input file and store them in a struct. And I think you can modify this code to match what you want to do easily.
If you have any questions please ask me to clarify.
Here is some part of the code to show how simple is the main:
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <mat_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while (mat_parse_next(file))
{
struct matrix *mat = mat_read(file);
mat_dump(mat);
mat_free(mat);
}
fclose(file);
return 0;
}

Related

C - read TXT change from dup to fgets and sscanf

I read from txt pairs of numbers
How check it only 2 numbers in each line and not 3. I want show the line is the problem for example the pairs file:
3
25 35
14 42
30 60 70
Console: illegal input at line 4
I know That's not the correct way at all. Need use fgets to read and sscanf to parse.
I tried but the memory full garbage. How can I change it correctly?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, c;
FILE *fp;
char str[100];
fp = fopen("./pairs.txt", "r");
if (dup2(fileno(fp), STDIN_FILENO < 0))
{
printf("Error opening file");
return -1;
}
if (feof(fp))
printf("Error reading file");
scanf("%d", &numOfPairs);
arrNum = (int *)malloc(sizeof(int) * numOfPairs * numbersInPair);
for (int i = 0; i < numOfPairs * numbersInPair; i += 2)
{
int num1, num2;
scanf("%d %d", &num1, &num2);
arrNum[i] = num1;
arrNum[i + 1] = num2;
}
}
Another try NOT working:
int main(int argc, char *argv[])
{
int index, i, numOfPairs;
int c;
FILE *file;
file = fopen("./pairs.txt", "r");
if ((c = getc(file)) == EOF)
{
perror("Error opening file"); //or return 1;
fclose(file);
}
while ((c = getc(file)) != EOF)
putchar(c);
{
fscanf(file, "%d", &numOfPairs);
allNumbers = (int *)malloc(sizeof(int) * numOfPairs * numbersInPair); //need multiply in 2 numbers for each pair
while (!feof(file) && numOfPairs > 0)
{
int x, y, arrIndex = 0;
numOfPairs--;
fscanf(file, "%d %d", &x, &y);
allNumbers[arrIndex] = x;
printf("The X : %d\n", x);
allNumbers[arrIndex + 1] = y;
printf("THE Y : %d\n", y);
arrIndex + 2;
}
fclose(file);
}

Question about writing and reading a 2D integer array to a text file

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);
}

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");
}

I am encountering a segmentation fault in my c code

I am trying to update a 2d array generation by generation.
In order to do this, I need to take two arguments: generation number and the initial input txt that contains a 2d array.
But no matter what I wrote, there are always segmentation fault in my code.
I am trying to read a 2d array from the input file.
The file should look similar to this:
1 1 1 0 0
0 0 0 0 0......
int main(int argc, char *argv[]) {
// take arguments//
char* generation;
char* filename;
if (argc < 2)
{
printf("Error\n");
exit(1);
}
else{
generation = argv[1];
filename = argv[2];
}
// read file as a 5*5 matrix//
FILE *file;
file = fopen (filename,"r");
//5*5 matrix//
int gen = atoi(generation);
int cell[5][5];
int i=0;
int j=0;
for (i=0;i<5;i++){
for (j=0;j<5;j++){
fscanf (file, "%d",&cell[i][j]);
}
}
fclose(file);
Thank you so much!!!
In your code you're not using the variable generation but I suppose it should be used to store the matrix dimension. If it is the case in total you're reading 3 arguments so argc should be 3.
If you are reading a file formatted like this:
1 2 3 4 5
6 7 8 9 10
1 1 3 4 5
6 7 8 9 0
The arguments passed at the console are: ./a.out dimension matrix. A simple but unsafe code (it doesn't check the dimension input by the user) is the following:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char *filename;
char *generation;
if (argc < 3)
{
printf("Error\n");
exit(1);
}
else {
generation = argv[1];
filename = argv[2];
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Error: Cannot open file %s for reading\n", filename);
exit(1);
}
}
int dim = atoi(generation);
int i, j, cell[dim][dim];
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
if (fscanf(fp, "%d ", &cell[i][j]) != 1) {
fprintf(stderr, "invalid input for cell[%d][%d]\n", i, j);
fclose(fp);
exit(1);
}
}
}
fclose(fp);
/*Print the matrix */
for (i = 0; i < dim ; i++)
{
for (j = 0; j < dim ; j++)
{
printf("%d ", cell[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}

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