Using remove function in c - 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;
}

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

How to save in a file in C

#include "Header.h"
void mostraTabuleiro(int lin, int col, int **m){
int i, j, l;
char k = 65;
for (l = 1; l <= col; l++){
printf("\t%c", k);
k++;
}
printf("\n");
for (i = 1; i <= lin; i++){
printf("%d", i);
for (j = 1; j <= col; j++){
if (i == lin && j == col)
printf("\t[X]");
else
printf("\t[*] ");
}
printf("\n");
}
}
and now i want to save the mostratabuleiro in a file and i started doing this
int GuardaFicheiro(char *nome_fich){
FILE *fnovo;
char *novo_fich = "estadosTabuleiro.txt";
fnovo = fopen(novo_fich, "wt");
if (fnovo == NULL){
printf("Erro ao abrir o ficehiro de texto %s para escrita.\n", novo_fich);
return;
}
//mostraTabuleiro(6, 8, Tabuleiro, fnovo);
fclose(fnovo);
}
if i put fprintf in the function mostraTabuleiro after that it doesn't appera anything and the file is blank.
This should be corrected
fnovo = fopen(novo_fich, "wt");
into:
fnovo = fopen(novo_fich, "w");
after that use fprintf();
fprintf(fnovo, /*source char * */);
You may please note that you should ask question on S.O. in this style. You can also read this.
void mostraTabuleiro(int lin, int col, int **m, FILE *fnovo) {
int i, j, k;
for (k = 1; k <= col; k++){
fprintf(fnovo, "\t%d", k);
}
fprintf(fnovo, "\n");
for (i = 1; i <= lin; i++){
fprintf(fnovo, "%d", i);
for (j = 1; j <= col; j++){
if (i == lin && j == col)
fprintf(fnovo, "\t[X]");
else
fprintf(fnovo, "\t[*] ");
}
fprintf(fnovo, "\n");
}
}
and
void GuardaFicheiro(int lines, int columns, int **m){
FILE *fnovo;
char *novo_fich = "estadosTabuleiro.txt";
fnovo = fopen(novo_fich, "wt");
if(fnovo == NULL){
printf("error opening file %s for writing.\n", novo_fich);
return;
}
// this will write to the file
mostraTabuleiro(lines, columns, m, fnovo);
// this will write on screen : stdout
mostraTabuleiro(lines, columns, m, stdout);
fclose(fnovo);
}
and
int iniciaJogo() {
tabuleiro tab;
int i, j, m, n;
int res = 0;
int **Tabuleiro;
int cont = 0;
int iteracoes = 0;
do{
do{
printf("Dimensoes do ambiente\nLines\n");
scanf("%d", &tab.N_Linhas);
} while (tab.N_Linhas < 4 || tab.N_Linhas > 8);
do{
printf("Columns\n");
scanf("%d", &tab.N_Colunas);
} while (tab.N_Colunas < 6 || tab.N_Colunas > 10);
} while (tab.N_Linhas > tab.N_Colunas);
Tabuleiro = criaTabuleiro(tab.N_Linhas, tab.N_Colunas);
GuardaFicheiro(tab.N_Linhas, tab.N_Colunas, Tabuleiro);
//mostraTabuleiro(tab.N_Linhas, tab.N_Colunas, Tabuleiro, fnovo);
}
And, may be main like:
int main(){
iniciaJogo();
return 0;
}
I am sure the above code would work for you. But you should read little about C Programming - functions, structures, and FileIO.
There are many unused variables in your code, you may check compiling your code with gcc -Wall -Wextra yourFileName.c

Can't read properly with fscanf

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

How do I continuously write to and read from the same file in C

I am trying to store the coordinates (x, y) in a text file, where x denotes the row number and y the column. I will then use this information to change the element of the array to 1, and the others will remain at 0. I want to do this multiple times to the same .txt file. I'm trying to simulate the famous Game of Life. The trouble is that is only successfully reads from the file once so the array cannot update, and so the array just prints off the same stuff as before.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 30
#define COLS 20
#define ITERATIONS 6
int fillBoard(int b[ROWS][COLS]);
int newRound(FILE *i, int b[ROWS][COLS]);
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]);
int cellBirth(FILE *p, int b[ROWS][COLS]);
int main(void) {
int board[ROWS][COLS];
char fileName[] = "#life 1.06";
int i, j;
int x, y;
int round = 0;
FILE *fp, *ifp;
char fileFormat[11];
int p, o;
fp = fopen("life.txt", "r");
ifp = fopen("life2.txt", "r");
if (fp == NULL) {
printf("Error\n");
exit(1);
}
if (ifp == NULL) {
exit(1);
}
fillBoard(board);
fgets(fileFormat, 11, fp); // read input from first line
if (strcmp(fileName, fileFormat) == 0) {
while (fscanf(fp, "%d %d", &x, &y) == 2) {
board[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
} else {
printf("Wrong file");
}
// print game with the starter cells
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", board[i][j]);
}
}
newRound(ifp, board);
fclose(fp);
fclose(ifp);
return(0);
}
int newRound(FILE *ij, int b[ROWS][COLS]) {
int round = 0;
int x, y;
int i, j;
while (round < ITERATIONS) {
printf("\n");
cellAliveOrDead(ij, b);
cellBirth(ij, b);
fillBoard(b);
while (fscanf(ij, "%d %d", &x, &y) == 2) {
b[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
round++;
// print game round 2
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", b[i][j]);
}
}
}
}
int fillBoard(int b[ROWS][COLS]) {
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
b[i][j] = 0;
}
}
}
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if(b[i][j] == 1) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if(count == 2 || count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
int cellBirth(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if (b[i][j] == 0) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if (count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
The simplest answer would be to use 2 files.
Write into a FILE* A. Then close it and read it as FILE* B, and write into a FILE* A. Repeat.
The other method would be to use fseek. This is quite risky as the chances of you rewriting on top of essential information is quite possible. But follow this answer, and you should be fine.
Also see this if you are curious about how fseek works.

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