I am trying to write a program will open a regular type file (binary or text/ASCII, read every byte in the file and write both the ASCII hex value for that byte as well as it’s printable (human-readable) character (characters, digits, symbols) to standard output. I am now just trying to let the user pick the file.
#include <stdio.h>
#include<stdlib.h>
FILE *file;
int main(int argc, char *argv[ ]){
int a;
int modified = 1;//1 means unmodified, 0 means modified
if(argc > 2){//writes to std error output
return 25;
}
if(argc == 2){// if there is 1 argument open it and read it
file = fopen(argv[1], "rt");
if(file == NULL){//cant open file. return error code 15
fprintf(stderr, "cant opent file %s \nerror code 15 \n", argv[1]);
return 15;
}
a = getc(file);
}else// get characters from stdin if no arguments
a = getchar();
char *buffer = malloc(200);
int j = 0;// buffer index helper
while( a != EOF){//reads character by character until EOF
if(j > 200){
j =0;
// fprintf(stderr,"error error, buffer overflow. \n error code 35 \n"); // send error to stderrl
// return 35;
}
I am getting errors though:
error: invalid conversion from `void*' to `char*'
xsd.cpp:30: error: expected `}' at end of input
xsd.cpp:30: error: expected `}' at end of input
The major problem is that you write C in a C++ program. C and C++ are similar, due to C++ inheriting from C, but they are ultimately different languages. For example, C++ have a harder and tougher type system, so you can't e.g. have implicit cast from void * to other pointer types like you can in C. In C++ you have to cast void * to the correct pointer, like e.g.
char *buffer = reinterpret_cast<char*>(malloc(200));
Even better would be to not write C code in C++, and use the C++ functionality like new/delete, the C++ input/output library, and classes like std::string for strings, etc.
Then there's of course the problem of you not having enough closing braces } at the end of the program. Did you not copy-paste all of the program?
Related
This is my code C/C++ code for writing a character to a file.
#include "mbed.h"
Serial pc(USBTX, USBRX);
char c;
char *cha = &c;
int main() {
FILE* WriteTo = fopen("/local/yourtext.txt", "w");
pc.printf("Write something and then press enter when finished...\n\r");
while (c != '\n') {
c = pc.getc();
pc.printf(cha);
fputc(c, WriteTo);
}
fclose(WriteTo);
pc.printf("File write successfull.\n\r");
}
The problem is that it doesn't work on my LPC1768. It only takes in one character and then I am unable to type anymore. I tried some other ways but none of the ways I tried allowed me to write to a file.
I'd like to also know if getc() empties out after I use putc. Does it have a limitation on the amount of characters I can write?
pc.printf(cha);
printf needs format argument to be null terminated char *.
But you are passing non null terminated char * thus by invoking undefined behavior.
Use:
pc.printf("%c", *cha); //Or pc.printf("%c", c);
Basically, I am trying to read binary data of a file by using fread() and print it on screen using printf(), now, the problem is that when it prints it out, it actually don't show it as binary 1 and 0 but printing symbols and stuff which I don't know what they are.
This is how I am doing it:
#include <stdio.h>
#include <windows.h>
int main(){
size_t sizeForB, sizeForT;
char ForBinary[BUFSIZ], ForText[BUFSIZ];
char RFB [] = "C:\\users\\(Unknown)\\Desktop\\hi.mp4" ; // Step 1
FILE *ReadBFrom = fopen(RFB , "rb" );
if(ReadBFrom == NULL){
printf("Following File were Not found: %s", RFB);
return -1;
} else {
printf("Following File were found: %s\n", RFB); // Step 2
while(sizeForB = fread(ForBinary, 1, BUFSIZ, ReadBFrom)){ // Step 1
printf("%s", ForBinary);
}
fclose(ReadBFrom);
}
return 0;
}
I would really appreciate if someone could help me out to read the actual binary data of a file as binary (0,1).
while(sizeForB = fread(ForBinary, 1, BUFSIZ, ReadBFrom)){
printf("%s", ForBinary); }
This is wrong on many levels. First of all you said it is binary file - which means there might not be text in it in the first place, and you are using %s format specifier which is used to print null terminated strings. Again since this is binary file, and there might not be text in it in the first place, %s is the wrong format specifier to use. And even if there was text inside this file, you are not sure that fread would read a "complete" null terminated string that you could pass to printf with format specifier %s.
What you may want to do is, read each byte form a file, convert it to a binary representation (google how to convert integer to binary string say, e.g., here), and print binary representation for each that byte.
Basically pseudocode:
foreach (byte b in FileContents)
{
string s = convertToBinary(b);
println(s);
}
How to view files in binary in the terminal?
Either
"hexdump -C yourfile.bin" perhaps, unless you want to edit it of course. Most linux distros have hexdump by default (but obviously not all).
or
xxd -b file
To simply read a file and print it in binary (ones and zeros), read it one char at a time. Then for each bit, print a '0' or '1'. Can print Most or Least significant bit first. Suggest MSb.
if (ReadBFrom) {
int ch;
while ((ch = fgetc(ReadBFrom)) != EOF) {
unsigned mask = 1u << (CHAR_BIT - 1); // CHAR_BIT is typically 8
while (mask) {
putchar(mask & ch ? '1' : '0');
mask >>= 1;
}
}
fclose(ReadBFrom);
}
I am trying to implement a function that reads txt files that contain 2 double and int per line with a space as a delimiter, for example (data.txt):
3.1 2.5 1
3.4 4.5 2
.....
I implemented the function below, it takes as arguments the file name, pointers to 2 double and an int. Each pointer will be used to retrieve a column from the file. I used
fgets
to get the line and then
sscanf
to extract the three values from the line. The program crushes at run time (error: Windows has triggered a breakpont in program.exe )
... When I put a breaking point before returning from the main function the retrieved values are corrected but the program crushes when I hit continue.
To debug the function I added the following lines of code to the function ReadFile below:
if (buf[strlen(buf)-1] != '\0')
{
putchar(buf[strlen(buf)-1]); //surprisingly this line prints 1 instead of a space...
exit(1);
}
With this change the code exit without reaching the end of the function. I don't understand this because the buf variable is long enough to hold all the characters of one line from the sample file.
I would appreciate your comments to fix this problem.
Thank you.
bool ReadFile(const char* fileName, double* x, double* y, int* t, int size)
{
FILE* fp;
char buf[5000];
fp = fopen( fileName, "r" );
for( int i = 0; i < size && fgets(buf, 5000, fp) != NULL; i++)
{
buf[strlen(buf)-1] = '\0';
if (buf[strlen(buf)-2] != '\0')
{
putchar(buf[strlen(buf)-1]);//surprisingly this line prints 1 instead of a space...
exit(1);
}
sscanf(buf, "%lf %lf %d", &x[i], &y[i], &t[i]);
}
fclose(fp);
return true;
}
The problem was in the caller, the size was set to 1 instead of the number of lines in the data file.
This is my code to bind a text file content to a linked list in C, the read job is ok but its made an error in fclose(f), Stack around the variable 'st' was corrupted. I don't understand it, how can I fix it?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <iostream>
using namespace std;
struct Nut
{
char Tu[7];
Nut * Tiep;
};
Nut TD[26];
Nut *first;
void AddFirst(Nut *q, Nut *&first)
{
Nut *p;
p = new Nut;
if (first == NULL)
{
first = q;
return;
}
for (p = first; p->Tiep != NULL; p = p->Tiep)
p->Tiep = q;
}
void ReadData(Nut *ds[], int &n)
{
n = 0;
char old = '0';
FILE *f;
Nut *Tam;
Nut *Tu;
f = fopen("TD.txt", "r");
int dem = -1;
if (f == NULL)
cout << "File rong !!!";
else
{
while (!feof(f) == 1)
{
char st[8] = "";
fscanf(f, "%s", st);
Tam = new Nut();
strcpy(Tam->Tu, st);
char c = st[0];
if (c != old){
dem++;
ds[dem] = new Nut();
n++;
}
AddFirst(Tam, ds[dem]);
}
}
fclose(f);
}
Update 1:
Sorry, I must do it in C, but I use Visual C++, the final environment is C
data file, td.txt
ACCEPT
ADULT
APART
AUGUST
BACK
BAD
BOY
BREAK
CAT
CHEF
CHICKEN
COWBOY
CRY
DAD
DESIGN
DIE
DRAW
EAT
EMPTY
ERROR
EXPLORE
FAN
FELL
FESTIVAL
FULL
GAS
GIVE
GRAPHIC
You use fscanf to read the strings into an array containing 8 characters, which means you can read string having 7 characters at most because the last character must be the special string-termination character '\0'.
However, in the input you have e.g. the string
FESTIVAL
which is exactly 8 characters, but needs 9 characters including the terminator. This will cause fscanf to write beyond the bounds of the array st.
What's worse is that you then copy this 9-character data into an array of only 7 characters, once again writing out of bounds.
Writing out of bounds of an array leads to undefined behavior, and makes your whole program ill-formed.
The most obvious problem: you're reading into a buffer of
8 char, but some of your data requires 9 (don't forget the trailing
'\0'); you then strcpy this into a buffer of 7 char. For the
input you give, you need buffers of at least 9 characters. You also
want to provide a width argument in the format of fscanf, in order to
avoid overwriting the buffer regardless of the input. (In fact, you
probably want to use fgets, to read line by line, with a very large
buffer, and then check that 1) you've actually read to the end of the
line (the last character should be a '\n'), and 2) that the word in
the line has at most one less characters than the size of your buffer.
(Obviously, this would all be significantly simpler in C++.)
I am trying to work out how I can print character by character the contents of a user-defined text file. I believe I have got the retrieval of the file correct but I am unsure how I can print each character.
#include <stdio.h>
#include <ctype.h>
#define ELEMENT 300
#define LENGTH 20
void main(char str[ELEMENT][LENGTH])
{
FILE *infile;
char textfile[1000];
char read_char;
int endoff;
int poswithin = 0;
int wordnum= 0;
printf("What is the name of your text file?: ");
scanf("%s", &textfile);
infile=fopen(textfile,"r");
if (infile == NULL) {
printf("Unable to open the file.");
}
else
{
endoff=fscanf(infile,"%c",&read_char);
while(endoff!=EOF);
{
This is where I believe I'm stuck. The first character is read into the variable read_char but then it doesn't seem to print anything?
if(read_char>=65&&read_char<=90 || read_char<=65)
{
str[wordnum][poswithin]=read_char;
printf("%c", read_char);
poswithin++;
}
else
{
str[wordnum][poswithin]=(char)"\n";
poswithin=0; wordnum++;
}
endoff=fscanf(infile, "%s", &read_char);
}
}
fclose(infile);
}
Typo in the format specifier to your second call to fscanf
endoff=fscanf(infile, "%s", &read_char);
should be
endoff=fscanf(infile, "%c", &read_char);
Also,
str[wordnum][poswithin]=(char)"\n";
shouldn't be casting a string literal to char and probably should be adding a NULL terminator rather than a newline:
str[wordnum][poswithin]='\0';
Finally, you shouldn't try to declare str as an argument to main.
char str[ELEMENT][LENGTH];
int main() // or int main(int argc, char* argv[])
Using fscanf with %c format specifier is overkill for reading a single character from a file.
Try fgetc to read one character. The function avoids the overhead of parsing a format specifier string and variable number of arguments.
A more efficient method is to allocate a buffer or array and read "chunks" of chars from a file, using fread. You can then scan the buffer or array. This has less function call overhead than many calls to read single bytes. Efficient buffer sizes are multiples of 512 to conform with disk drive sector sizes.