How to Perform Bitwise Operations on File Data in C?

0
6
Asked By CodeNinja42 On

I'm trying to create a program that reads a file and prints its binary content byte by byte into an array. I'm new to programming and would appreciate any constructive feedback on my code. I've successfully implemented this for simple variable types but am struggling with how to manage file data. Specifically, I'm having trouble performing bitwise operations on the input file data. Here's what I have so far:

```c
#include

void BitPrint(char FileName[100]){
FILE *FileStartP;
FILE *FileEndP;
FileEndP = FileStartP;
FileStartP = fopen(FileName, "r");
fseek(FileEndP, 0, SEEK_END);
int size = ftell(FileEndP);
printf("%d", size);

int BitList[8][size];
int BitNum = 0;
for (int y = 0; y < ((sizeof(BitList) / sizeof(BitList[0][0])) / 8); y++){
for (int x = 0; x > BitNum) & 1);
BitNum++;
}
}

for (int y = 0; y < ((sizeof(BitList) / sizeof(BitList[0][0])) / 8); y++){
for (int x = 0; x > (have 'FILE' and 'int')." I'm trying to use the file pointer in the bitwise operation, but I'm not sure if I'm doing it correctly. Any advice would be greatly appreciated!

2 Answers

Answered By CuriousCoder88 On

You can't perform bitwise operations on a file pointer itself since it doesn’t point directly to the data in memory. Instead, it’s a reference to a structure that manages the file. Instead, read from the file using functions like `fgetc` which gives you the actual byte values you can manipulate. For example:

```c
char value;
for (int y = 0; y < size; y++) {
value = fgetc(FileStartP);
if (value != EOF) {
for (int x = 0; x > x) & 1);
}
}
}
```

This way, you're correctly processing the data from the file. Also, storing data as bits might not be necessary at this point; consider using an array of bytes instead and handle bit manipulation when actually printing!

Answered By LearnWithMe123 On

You're right about misunderstanding file pointers! They don't work like regular pointers that point to memory locations. After using `fseek`, make sure to reset your pointer back to the start of the file using `rewind(FileStartP);` before reading. You’ll access file data through functions like `fgetc(file)` or `fread()`. After getting the bytes, you can perform bitwise operations on them later. Check out some tutorials on file I/O in C for more details. Here's a few links that might help:
- https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm
- https://dev.to/mikkel250/reading-files-contents-in-c-ma9

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.