Can't read properly with fscanf - c

I have the following difficulties. I'm trying to read this file.
3
1 2 3
2
4 5
The numbers that are alone are the size of the array (3 and 2). And the following numbers are the array.
So 3 is the size of (1,2,3) and 2 is the size of (4,5).
I wrote a code on C to read that numbers and store them in arrays that use malloc().
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main(){
int i=0, j, *size, *vector;
size=(int*)malloc(sizeof(int));
vector=(int*)malloc(sizeof(int));
FILE *file;
file=fopen("file.dat", "rt");
if (file==NULL){
printf("Exit ...");
exit(1);
}
else {
do{
fscanf(file,"%d",&size[i]);
for(j=0;j<=size[i];j++){
fscanf(file,"%d",&vector[j]);
}
i++;
}while(feof(file)==0);
}
fclose(file);
return 0;
}
Is reading the file properly but if I printf the numbers I get:
3
5
2
3
4
2

Two things to mention here.
You have allocated memory for only one variable through malloc(), but you try to access beyond the allocated memory in the do...while loop. You need to realloc(), as and when required.
Please see Why is “while ( !feof (file) )” always wrong?

#include <stdio.h>
#include <stdlib.h>
int main(void){
int i, j, size, *size_v, **vector;
FILE *file;
file=fopen("file.dat", "rt");
if (file==NULL){
printf("Exit ...");
exit(1);
}
i = 0;//scan file
while(EOF != fscanf(file, "%d", &size)){
for(j = 0; j < size; j++){
fscanf(file, "%*d");
}
i++;
}
rewind(file);
size_v = malloc(i * sizeof(int));
vector = malloc(i * sizeof(int*));
i = 0;//read file
while(EOF != fscanf(file, "%d", &size_v[i])){
vector[i] = malloc(size_v[i] * sizeof(int));
for(j = 0; j < size_v[i]; j++){
fscanf(file, "%d", &vector[i][j]);
}
i++;
}
fclose(file);
//print & deallocate
size = i;
for(i = 0; i < size; ++i){
printf("%d\n", size_v[i]);
for(j = 0; j < size_v[i]; ++j){
printf("%d ", vector[i][j]);
}
printf("\n");
free(vector[i]);
}
free(vector);
free(size_v);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i, j, size, *vector;
FILE *file;
file=fopen("file.dat", "rt");
if (file==NULL){
printf("Exit ...");
exit(1);
}
i = 0;
while(EOF != fscanf(file, "%d", &size)){
printf("%d\n", size);//each loop
vector = malloc(size * sizeof(int));
for(j = 0; j < size; j++){
fscanf(file, "%d", &vector[j]);
}
for(j = 0; j < size; j++){
printf("%d ", vector[j]);
}
printf("\n");
free(vector);
i++;
}
fclose(file);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i, j, k, size, size_sum, *size_v, *vector;
FILE *file;
file=fopen("file.dat", "rt");
if (file==NULL){
printf("Exit ...");
exit(1);
}
i = 0;//scan file
size_sum = 0;
while(EOF != fscanf(file, "%d", &size)){
size_sum += size;
for(j = 0; j < size; j++){
fscanf(file, "%*d");
}
i++;
}
rewind(file);
size_v = malloc(i * sizeof(int));
vector = malloc(size_sum * sizeof(int));
i = 0;//read file
k = 0;
while(EOF != fscanf(file, "%d", &size_v[i])){
for(j = 0; j < size_v[i]; j++){
fscanf(file, "%d", &vector[k++]);
}
i++;
}
fclose(file);
//print & deallocate
size = i;
size_sum = 0;
for(i = 0; i < size; ++i){
printf("%d\n", size_v[i]);
for(j = 0; j < size_v[i]; ++j){
printf("%d ", vector[j + size_sum]);
}
printf("\n");
size_sum += size_v[i];
}
free(vector);
free(size_v);
return 0;
}

Related

I tried to compile and run the following bubble sort program using the gcc but it shows the error

{
int *v;
int i=0;
int n;
int j=0;
int aux=0;
File *fp;
fp = fopen("Inteiros.txt", "r"); /*opening a file and read it*/
if(fp == NULL)
printf("Erro, ficheiro nao encontrado!\n");/*portuguese sentence*/
else
while(!feof(fp))
{
fscanf(fp, "%d", &v[i]);
i++;
}
for(i=1; i<n; i++)
{
for(j=0; j< n-i-1; j++)
{
if(v[j] > v[j+1])
{
aux = v[j];
v[j] = v[j+1];
v[j+1] = aux;
}
}
}
than gave me the "segmentation fault" error and I don't know why.
I know its a piece of the memory that I don't have access, but I don't know where is the error.
You're likely getting a seg fault because you didn't allocate any memory for you pointer int *v and then you try to assign values to it like it's an array. Also int n; was never initialized so your getting into undefined behavior. Also File is not a type unless you made your own that you're not showing, should be FILE.
Try something like this:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMS 1024
int main()
{
int *v;
int i=0, j=0, aux=0, n = 0;
FILE *fp;
fp = fopen("Inteiros.txt", "r");
if(fp == NULL) {
printf("Erro, ficheiro nao encontrado!\n");
return 1;
}
else {
//allocate memory for v
if ((v = malloc(sizeof (int) * MAX_NUMS)) == NULL) {
printf("Error in malloc\n");
return 1;
}
while(!feof(fp)) {
fscanf(fp, "%d", &v[i]);
i++;
}
//number of lines read
n = i;
for(i = 0; i < n; i++) {
for(j = 0; j < n-i-1; j++) {
if(v[j] > v[j+1]) {
aux = v[j];
v[j] = v[j+1];
v[j+1] = aux;
}
}
}
for (i = 0; i < MAX_NUMS; i++)
printf("v[%d] is %d\n", i, v[i]);
}
return 0;
}

Using remove function in c

I have a problem with the remove() function. It is very simple program will copy the 2d matrix into kimenet.txt and I want to remove the bemenet.txt.
The question : why my program return -1 when it should be 0 ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a,n,i,j;
FILE *fin,*fout;;
fin = fopen("bemenet.txt","rt");
if(!fin){printf("Error");return EXIT_FAILURE;}
fout = fopen("kimenet.txt","wt");
if(!fout){printf("Error");return EXIT_FAILURE;}
fscanf(fin,"%i",&n);
a = (int**)malloc(n*sizeof(int*));
for(i = 0; i < n; ++i){
a[i] = (int*)malloc(n*sizeof(int));
for(j = 0; j <n; ++j){
fscanf(fin,"%i",&a[i][j]);
}
}
for(i = 0; i < n; ++i){
for(j = 0; j < n; ++j){
fprintf(fout,"%4i ",a[i][j]);
}
fprintf(fout,"\n");
}
int ret = remove("kimenet.txt");
if(ret == 0){
printf("Deleted succesfully");
}
else printf("Error");
fclose(fin);
fclose(fout);
return EXIT_SUCCESS;
}
You can't delete a file without closing it... use fclose to close the file first.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a, n, i, j;
FILE *fin, *fout;;
fin = fopen("bemenet.txt", "rt");
if (!fin){ printf("Error"); return EXIT_FAILURE; }
fout = fopen("kimenet.txt", "wt");
if (!fout){ printf("Error"); return EXIT_FAILURE; }
fscanf(fin, "%i", &n);
a = (int**)malloc(n*sizeof(int*));
for (i = 0; i < n; ++i){
a[i] = (int*)malloc(n*sizeof(int));
for (j = 0; j <n; ++j){
fscanf(fin, "%i", &a[i][j]);
}
}
for (i = 0; i < n; ++i){
for (j = 0; j < n; ++j){
fprintf(fout, "%4i ", a[i][j]);
}
fprintf(fout, "\n");
}
fclose(fin); //move fcloses here
fclose(fout);
int ret = remove("kimenet.txt");
if (ret == 0){
printf("Deleted succesfully");
}
else printf("Error");
return EXIT_SUCCESS;
}

How to read integer numbers from file to an array?

An error always occurs just like (stream != null)
What does it mean?
I shoul write a program then reads numbers to an array that prints them out. Otherwise everything will be bad(
#include <stdio.h>
#define M 4
int main() {
int i = 0, b = 0;
int myArray[M];
FILE *myFile;
myFile = fopen("D:\file1.txt", "rt");
for (i = 0; i < M; i++) {
fscanf(myFile, "%d", myArray[i]);
}
fclose(myFile);
for (i = 0; i < M; i++) {
printf("%d", &myArray[i]);
}
return 0;
}

Reading multi-line characters from a text file

I have to read a maze from a file and store it in a twodimensional array.
The characters I'm reading are stored in a .txt file like this:
######
#....#
#..#.#
. .#..
######
Note that the number of rows and columns can vary depending on the file.
My approach in reading the file so far:
#include <stdio.h>
#include <stdlib.h>
void read_arr(char** a, int x_size, int y_size) {
int i, j;
int tmp;
FILE* file = fopen("lab1.txt", "r");
for (i = 0; i < y_size; i++) {
for (j = 0; j < x_size; j++) {
if (tmp = fgetc(file))
a[j][i] = tmp;
printf("Success\n");
}
}
}
void print_arr(char** a, int x_size, int y_size) {
int i, j;
for (i = 0; i < x_size; i++) {
for (j = 0; j < y_size; j++) {
printf("%c", a[i][j]);
}
printf("\n");
}
}
int main() {
int x_size, y_size;
printf("What is the size of the maze (<x> <y>)? ");
scanf("%d %d", &x_size, &y_size);
printf("Maze has size %dx%d\n", x_size, y_size);
char** a = malloc(sizeof(char) * (x_size * y_size));
if (!a)
return -1;
printf("Successfully allocated memory!\n");
read_arr(a, x_size, y_size);
print_arr(a, x_size, y_size);
return 0;
}
But all I get from this is a memory error (I'm afraid I cant't give the exact error message, because it is displayed in german).
Another thing I've tried is using fscanf, but that didn't work either.
I'm on Ubuntu, and using gcc to compile my code.
Any help would be much appreciated!
Memory allocation is not correct
char** a = malloc(sizeof(char) * (x_size * y_size));
I guess what you wanted to do is
char** a = malloc(sizeof(char*) * y_size);
for(i = 0; i < y_size; ++i)
a[i]=malloc(x_size);
Also in read_arr function, you access array as arr[j][i], while j is your inner index, and i is outer
for (i = 0; i < y_size; i++) {
for (j = 0; j < x_size; j++) {
if (tmp = fgetc(file))
a[j][i] = tmp; ==> a[i][j] = tmp;
printf("Success\n");
}
}

Reading two matrices from one txt file

I'm having trouble with one task.
I need to read two matrices from a text file and multiply them together.
The problem is that I know how to read one matrix but I don't understand how to read the two matrices separated (for example) by two spaces in a file.
Matrix.txt:
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
Maybe someone could explain me how to do that.
Now i'm trying to read first matrix:
#include <stdlib.h>
#include <stdio.h>
int main(){
FILE *fp;
int eSk = 0, sSk = 0,
matrix1[10][10] = {0}, i, j;
char c;
fp = fopen("matrix.txt", "r+");
while(!feof(fp)) {
while(getc(fp) != ' ') {
fscanf(fp, "%d", &matrix1[eSk][sSk]);
sSk++;
}
eSk++;
}
for(i = 0; i < eSk; i++) {
for(j = 0; j < sSk; j++) {
printf("%d ", matrix1[eSk][sSk]);
}
printf("\n");
}
puts("");
system("pause");
return 0;
}
what's wrong ?
Thank you for any help.
You need to skip the second matrix while reading the first and viceversa. Try this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *file;
int matrixA[3][3], matrixB[3][3];
int garbage[3];
int i, j, k;
i = j = k = 0;
file = fopen("matrix.txt", "rt");
/* Read the first matrix */
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
fscanf(file, "%d", &matrixA[i][j]);
}
/* Skip the second matrix */
for (k = 0; k < 3; k++) fscanf(file, "%d", &garbage[k]);
}
/* Reposition the stream */
fseek(file, 0, SEEK_SET);
/* Read the second matrix */
for (i = 0; i < 3; i++) {
/* Skip the first matrix */
for (k = 0; k < 3; k++) fscanf(file, "%d", &garbage[k]);
for (j = 0; j < 3; j++) {
fscanf(file, "%d", &matrixB[i][j]);
}
}
/* Multiply them ... */
/* Show first matrix */
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf(" %d ", matrixA[i][j]);
}
}
printf("\n");
/* Show second matrix */
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf(" %d ", matrixB[i][j]);
}
}
return 0;
}
If the format of the string is standardized, you can read both matrices at one go. For your example above, please find a modified version as below.
int main(){
FILE *fp;
int eSk = 0, sSk = 0, i, j;
int mat1[3][3], mat2[3][3];
char line[256];
char c;
fp = fopen("matrix.txt", "r+");
if(NULL == fp) {
printf("Can't open the file\n");
exit(-1);
}
// Read one line
fgets(line, 256, fp);
while(!feof(fp)) {
// Convert line to array
sscanf(line,"%d %d %d %d %d %d", &mat1[eSk][0], &mat1[eSk][1], &mat1[eSk][2], &mat2[eSk][0], &mat2[eSk][1], &mat2[eSk][2]);
// Increment counter
eSk++;
//Read next line
fgets(line, 256, fp);
}
printf("Matrix1\n");
for(i = 0; i < eSk; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", mat1[i][j]);
}
printf("\n");
}
printf("Matrix2\n");
for(i = 0; i < eSk; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", mat2[i][j]);
}
printf("\n");
}
puts("");
system("pause");
return 0;
}

Resources