Does the r+ C mode for files not create the file if it does not exist?

Asked

Viewed 164 times

1

I am working on this code below and would like to store some random vectors in a file. From what I read the r+ mode reads the file and writes to it, and if it doesn’t exist it will be created. Well... It turns out that when I use the code the way it is it can’t create a file, it simply goes into the condition that defines an error when creating the file, but when I change the mode from "r+" to "w+", it creates the file and works right, I wonder if what I read about the "r+" is wrong or is it something that is wrong in my program and I’m not seeing.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define tam 1000000

int main (){
    //declaração de variáveis
    FILE * arq = NULL;
    int i,array_size,v[tam];

    //lendo o tamanho do vetor e a quatidade de vetores a serem gerado
    printf("Digite o tamanho do vetor a ser gerado : \n");
    scanf ("%d",&array_size);

    //criando arquivo para armazenar os vetores gerados
    arq = fopen("vetoresgerados","r+");
    if (arq == NULL){
        printf ("Erro ao abrir o aquivo\n");
        return 0;
    }

    //gerando vetores aleatórios
    srand (time(0));
    for (i = 0; i < array_size;i++){
        v[i] = rand()%1000;
    }

    for (i = 0; i < array_size;i++){
        fprintf(arq, "%d ",v[i]);
    }
    fclose(arq);
    return 0;
}

1 answer

0


Browser other questions tagged

You are not signed in. Login or sign up in order to post.