fread does not read the entire file - c

I used fread to read the entire file but I am getting only the first of it, why is that?
My code:
#define MAXBUFLEN 4096
int main(){
int ret =0;
char source[MAXBUFLEN + 1];
FILE *fp = fopen("test", "r");
if (fp != NULL)
{
rewind(fp);
ret = fread(source, 1, MAXBUFLEN, fp);
printf("ret : %d %s",ret,source);
fclose(fp);
}
return 0;
}
The file text:
/# cat test
/usr/sbin/sshd-p 1234-o LoginGraceTime=30-o ClientAliveInterval=600-o ClientAliveCountMax=0-o TCPKeepAlive=no-o MaxSessions=1-o MaxStartups=1-o MaxAuthTries=3
My program output :
ret : 167 /usr/sbin/sshd
What is the easiest way of reading this entire file? (which is not standard and not end with \n)?

Answer : there was 0 between each word in this file, it was not standard word but ^# which is recored seperate in Linux . The code was fixed by this:
#include <stdio.h>
void removeNewLine(char * str,int len);
#define MAXBUFLEN 4096
int main(){
char source[MAXBUFLEN + 1];
FILE *fp = fopen("test", "r");
int ret =0;
if (fp != NULL)
{
rewind(fp);
ret = fread(source, 1,MAXBUFLEN, fp);
removeNewLine(source,ret);
fclose(fp);
}
return 0;
}
void removeNewLine(char * str,int len){
int i=0;
for(i=0; i<len;i++) {
if((int)str[i]==0 )
{
str[i]=' ';
}
}
str[len] = 0;
printf("%s",str);
}

Related

Load string containing words from file

I need to load strings from file into a struct array.
CORRECT OUTPUT:
4
Sarajevo,345123
Tuzla,123456
Mostar,101010
Banja Luka,234987
MY OUTPUT:
1
Sarajevo 345123
Tuzla 123456
Mostar 101010
Banja Luka 234987,544366964
Code:
#include <stdio.h>
#include <string.h>
struct City {
char name[31];
int number_of_citizen;
};
int load(struct City cities[100], int n) {
FILE *fp = fopen("cities.txt", "r");
int i = 0;
while (fscanf(fp, "%[^,]s %d\n", cities[i].name, &cities[i].number_of_citizen)) {
i++;
if (i == n)break;
if (feof(fp))break;
}
fclose(fp);
return i;
}
int main() {
int i, number_of_cities;
struct City cities[10];
FILE* fp = fopen("cities.txt", "w");
fputs("Sarajevo 345123", fp); fputc(10, fp);
fputs("Tuzla 123456", fp); fputc(10, fp);
fputs("Mostar 101010", fp); fputc(10, fp);
fputs("Banja Luka 234987", fp);
fclose(fp);
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
Could you explain me how to fix this? Why my program only loaded 1 city?
The fscanf() conversion string is incorrect: instead of "%[^,]s %d\n" you should use:
while (i < n && fscanf(fp, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
}
Or better:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
char ch[2];
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
if (sscanf(buf, "%30[^,],%d%1[\n]",
cities[i].name,
&cities[i].number_of_citizen, ch) == 3) {
i++;
} else {
fprintf(stderr, "invalid record: %s\n", buf);
}
}
fclose(fp);
return i;
}
Also change your main function to output commas between the city names and population counts:
int main() {
int i, number_of_cities;
struct City cities[10];
FILE *fp = fopen("cities.txt", "w");
if (fp) {
fputs("Sarajevo,345123\n", fp);
fputs("Tuzla,123456\n", fp);
fputs("Mostar,101010\n", fp);
fputs("Banja Luka,234987\n", fp);
fclose(fp);
}
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
EDIT: since there are no commas in the database file, you must use a different parsing approach:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
/* locate the last space */
char *p = strrchr(buf, ' ');
if (p != NULL) {
/* convert it to a comma */
*p = ',';
/* convert the modified line */
if (sscanf(buf, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
continue;
}
}
fprintf(stderr, "invalid record: %s", buf);
}
fclose(fp);
return i;
}

Strange characters when reading from file in C

So I am just trying to learn C and have decided to program a simple calendar where you can add events etc. It is working almost perfectly however, when it tries to read from the file containing the information, the first line contains some strange characters : �<�}�U1.
Code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void createCalendar(char filename[]) {
FILE *cptr;
cptr = fopen(filename, "w");
char dates[177/sizeof(char)] = "";
for(int i = 1; i < 32; i++) {
char strtowrite[7/sizeof(char)] = "";
sprintf(strtowrite, "%d - \n", i);
strcat(dates, strtowrite);
}
fprintf(cptr, "%s", dates);
fclose(cptr);
}
void addToDay(char filename[], int day, char event[]) {
FILE *cptr;
cptr = fopen(filename, "r");
char *line = NULL;
size_t len = 0;
ssize_t read;
char dates[177/sizeof(char) + strlen(event)/sizeof(char)];
int i = 1;
while ((read = getline(&line, &len, cptr)) != -1) {
if (i==day) {
char strtowrite[7/sizeof(char) + strlen(event)/sizeof(char)];
sprintf(strtowrite, "%d - %s\n", i, event);
strcat(dates, strtowrite);
}
else {
strcat(dates, line);
}
i += 1;
}
printf("%s", dates);
fclose(cptr);
cptr = fopen(filename, "w");
fprintf(cptr, "%s", dates);
fclose(cptr);
}
int main() {
createCalendar("january");
addToDay("january", 12, "event");
}
and the first line of output is: í¬_<89>lU1 - (in the file)
Try this
char dates[177/sizeof(char) + strlen(event)/sizeof(char)] = {0};
in your addToDay function when declaring the dates variable. I think that you do not set the memory there, so there might be some junk in that memory location.

Reading txt file with fscanf( Problems with fscanf reading strings line by line)

Contents of input.txt:
Xanthos
Myra
Phaselis
Contents of input2.txt:
askjdkdanmowflfkadkjkaksdklskksadllasd
fkfklsal;sdlslfsdkdfkMyraslfsfeokdlasdfdf
wfewfPsdflsdfklsdosfkeowkfweofkwoefkkfsf
sdfsdakjewofksdfoiwefjowefks;dfPhaselissdfkefowefjksdlfjslfjsldfj
oefkwtifjslflsdfkjeifjsl;asldkiefjiefjlskfdjeifjksk
output.txt:Xanthos(8,9)
Myra(2,22)
Phaselis (4,32)
I wrote a program that searches for the string inside the input at input 2, finds its location and writes it to the output. It prints only the position of the first string(Xanthos (8,9).Could the problem be related to whitespaces?Expected output.txt as above, but the output I received only has Xanthos (8,9).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE_2 150
int indexOfhor(FILE *fptr, const char *word, int *line, int *col);
int main(){
FILE *fptr;
FILE *fptr1;
FILE *fptr2;
int line ,col;
char word[10];
fptr = fopen("input.txt","r");
fptr1= fopen("input2.txt", "r");
fptr2= fopen("output.txt","a");
while (fscanf(fptr, "%s", word) != EOF ) {
//rewind(fptr1) after adding this problem is solved
indexOfhor(fptr1, word, &line, &col );
if(line != -1 ){
fprintf(fptr2,"%s (%d,%d)\n", word, line + 1, col + 1);
}
else if(line==-1) continue;;
}
fclose(fptr);
fclose(fptr1);
fclose(fptr2);
return 0;
}
int indexOfhor(FILE *fptr, const char *word, int *line, int *col){
char str[BUFFER_SIZE_2];
char *pos;
*line = -1;
*col = -1;
while ((fgets(str, BUFFER_SIZE_2, fptr)) != NULL)
{
*line += 1;
pos = strstr(str, word);
if (pos != NULL){
*col = (pos - str);
break;
}
}
// If word is not found then set line to -1
if (*col == -1)
*line = -1;
return *col;
}

Trying to read from a file that I know exists and is good but will not open

When I try to open a file "canbus.txt.txt" it is coming back with an error message that reads out "error: No error" repeatedly. I cannot find where this issue would be coming from. My file is in the main project directory and the name and extensions are all correct.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int i;
char value;
char test[60];
char *line;
int num = 0;
int address[25];
int values[25];
void ms_delay (int N)
{
T1CON = 0x08030;
int delay = N * 62.5; // 1 Milisecond => .001 / (256 * (1/16,000,000)) = 62.5
TMR1 = 0;
while (TMR1 < delay);
}
int main (void)
{
PIN_MANAGER_Initialize();
UART1_Initialize();
ECAN1_Initialize();
ECAN1_ReceiveEnable();
INTERRUPT_Initialize();
FILE *fp;
char* filename = "canbus.txt.txt";
fp = fopen(filename, "r");
if(fp == NULL){
perror("Error");
exit(EXIT_FAILURE);
}
while(fgets(line, sizeof(line), fp)){
fscanf(fp, "%lf %lf", &address[num], &values[num]);
sprintf(test, "Value = %lf Other = %lf", address[num], values[num]);
int i = 0;
while(test[i] != '\0'){
UART1_Write(test[i]);
i++;
}
++num;
}
ms_delay(250);
UART1_Write(0x0D);
UART1_Write(0x0A);
fclose(fp);
return 0;
}
#include <stdio.h>
int main()
{
FILE *fr;
char c;
fr = fopen("prog.txt", "r");
while( c != EOF)
{
c = fgetc(fr); /* read from file*/
printf("%c",c); /* display on screen*/
}
fclose(fr);
return 0;
}
To know more https://www.codesdope.com/c-enjoy-with-files/

Writing to a text file through the CMD window and a C exe?

I was wondering how I can get this code to overwrite a textfile from it's text value to it's ASCII value.
I want it to do something like this:
CMD > c:\users\username\desktop>cA5.exe content.txt
content.txt has "abc" in it and I want the command line to change the "abc" to it's ASCII values. 97... etc. I don't want anything written in the command window, I want it to change in the text file. Is this possible, if so, how could I do it with this existing code?
#include <stdio.h>
#include <stdlib.h>
int main(int argc[1], char *argv[1])
{
FILE *fp; // declaring variable
fp = fopen(argv[1], "rb");
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
Not the best code but very simple.
#include <stdio.h>
#include <stdlib.h>
void convertToAHex(char *data, long int size, FILE *file){
rewind(file);
int i;
for(i = 0; i < size; ++i){
fprintf(file, "%d ", data[i]);
}
}
int main(int argc, char *argv[]){
if(argc != 2){
return EXIT_FAILURE;
}
FILE *file = fopen(argv[1], "r+");
if(file){
char *data;
long int size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
data = (char *) calloc(size, sizeof(char));
if(data){
fread(data, 1, size, file);
convertToAHex(data, size, file);
free(data);
}
fclose(file);
}
return EXIT_SUCCESS;
}

Resources