0
votes

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

2
Did you include the proper header files? What does gcc say when -Wall is passed to it? Where does the error occur when you run strace against it? - alvits
The filename in fopen() is relative path. Does the path exist? Did you check if fopen() returns non-NULL file desc? - alvits
I just checked and 'fopen()' returns a NULL file. My header fies are '#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <stdint.h> #include <string.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h>' - Juan Bravo
fopen() return NULL because it can't create file in inexistent directory. Use full path instead of relative path in specifying file. Or don't specify a path and file will be created in current working directory. - alvits

2 Answers

1
votes

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");
1
votes

You have missed out the file pointer from the fprintf statement

fprintf("Datos leidos del sensor");

Try

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