Juan Bravo
Juan Bravo

Reputation: 33

Error: Segmentation fault using fopen and open

I'm connecting a BeagleBoneBlack with a IMU using I2C protocol. I already read data in console great but when im trying to store data in a .txt file, it return me error: Segmentation fault.

int I2C_open()
{
    int file;
    char *dev = "/dev/i2c-1";
    if ((file=open(dev,O_RDWR))<0);
    {
        perror("Abrir el canal");
    }
    return file;
}

int main()
{
    archivo=I2C_open();
    f=fopen("./home/debian/Desktop/Comunicacion/Prueba.txt","W");
    fprintf(f,"Datos leidos del sensor");
}

This is just part of the code because it's large. The problem is presented when i use the fprintf, when i commented that line the code run well. Im not sure if is because im using fopen while "/dev/i2c-1" is running. Please help

Upvotes: 0

Views: 1183

Answers (2)

Craig Estey
Craig Estey

Reputation: 33601

Note: You used "W" instead of "w" as the open mode to fopen. That's the real problem.

But, you should always check the "f" variable for NULL after the fopen. I'm fairly sure that it's NULL [which means you couldn't open the file]. This is just good practice. It's much easier than tracking down a segfault.

You have:

f=fopen("./home/debian/Desktop/Comunicacion/Prueba.txt","W");
fprintf(f,"Datos leidos del sensor");

Change this to:

f=fopen("./home/debian/Desktop/Comunicacion/Prueba.txt","w");
if (f == NULL) {
    perror("fopen");
    exit(1);
}
fprintf(f,"Datos leidos del sensor");

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34585

You have missed out the file pointer from the fprintf statement

fprintf("Datos leidos del sensor");

Try

fprintf(f, "Datos leidos del sensor");

Upvotes: 1

Related Questions