C number of characters on file - c

Why is my program returning me 9 when the file has "test1" written?
The program looks for number of characters within the file. I wanted to run off the 'while(fgetc(file) != EOF)' method but this seems not to be working.
I would appreciate some help on this. Thank you
#include <stdio.h>
#include <stdlib.h>
#define FORMATLOG "FORMAT ERROR: invalid parameter: s5e4 <filename.txt>"
#define TXFILELOG "FILE ERROR: Can't open file or file does not exist"
enum { true, false };
int interface(char *filename) {
FILE *f_text = fopen(filename, "r+");
size_t size;
char c;
if(f_text == NULL) {
puts(TXFILELOG);
return NULL;
}
fseek(f_text, 0, SEEK_END);
size_t length = (size_t) ftell(f_text);
printf("%d", length);
fclose(f_text);
return true;
}
int main(int argc, char **argv) {
if(argc != 2) {
puts(FORMATLOG);
return false;
}
return interface(argv[1]);
}

Why the complication??
See http://linux.die.net/man/2/stat
i.e.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
struct stat buf;
stat("filename", &buf);
printf("Size:%d\n", buf.st_size);
return 0;
}
(oops missed out the error check but I guess you get the picture)

Related

C fwrite appearently doesn't write numbers

I'm trying to write a struct into a .txt file, but fwrite seems to not work as expected: I expected the file file.txt to show Jhonny 18 10.0, but it doesn't, am I missing something?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "file.txt"
typedef struct {
char name[32];
int age;
float value;
} Test_struct;
int main(int argc, char** argv)
{
Test_struct test;
strcpy(test.name, "Jhonny");
test.age = 18;
test.value = 10.0;
FILE* file = fopen(FILENAME, "w");
if (file == NULL)
{
fprintf(stderr, "\nAn error occurred while opening the file\n");
return -1;
}
if (fwrite(&test, sizeof(test), 1, file) < 0)
return -1;
fclose(file);
return 0;
}
And here's the resulting file:
I've followed this tutorial.
It turned out that fwrite() isn't the right function to do what I want (write to a .txt file), so WhozCraig suggested me to use fprintf() instead, and that's the resulting code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "file.txt"
typedef struct {
char name[32];
int age;
float value;
} Test_struct;
int main(int argc, char** argv)
{
Test_struct test;
strcpy(test.name, "Jhonny");
test.name[7] = '\0';
test.age = 18;
test.value = 10.0;
FILE* file = fopen(FILENAME, "w");
if (file == NULL)
{
fprintf(stderr, "\nAn error occurred while opening the file\n");
return -1;
}
if (fprintf(file, "%s %d %3.2f", test.name, test.age, test.value) < 0)
return -1;
fclose(file);
return 0;
}
Result:

Selecting random line from array c

So far I have read all my data into an array
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
int main(void) {
int i=0;
char* string[100];
char line[100];
FILE *file;
file = fopen("plates.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
printf("%s",line);
string[i]=line;
i++;
}
fclose(file);
return 0;
}
but i want to now select a random line of my array and print it. All lines need to have an equal chance of being selected but they can only be selected once. Im not too sure how to do this...
Thank you in advance
Please be mindful of this line string[i]=line as it makes all the array entries in string that you set all point to the last line read which is not what you want and it's pretty important to understand that.
That said, here's a solution to the problem that assumes we can just store all the lines in memory and on the stack:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_LINE_LENGTH 128
#define MAX_LINE_COUNT 1000
int main(int argc, char **argv) {
char lines[MAX_LINE_COUNT][MAX_LINE_LENGTH];
int numLines = 0;
if (argc < 2) {
fprintf(stderr, "missing file name\n");
return EXIT_FAILURE;
}
FILE *fp = fopen(argv[1], "r");
if (fp != NULL) {
while (fgets(lines[numLines++], MAX_LINE_LENGTH, fp)) {
printf("%03d> %s", numLines, lines[numLines-1]);
}
fclose(fp);
srand (time(NULL));
int randomIndex = rand() % numLines;
printf("Selected random line #%d> %s", randomIndex+1, lines[randomIndex]);
} else {
fprintf(stderr, "file '%s' not found\n", argv[1]);
return EXIT_FAILURE;
}
}
And the corresponding output:
➜ ~ gcc random-line.c && ./a.out random-line.c
001> #include <stdio.h>
002> #include <stdlib.h>
003> #include <string.h>
004> #include <time.h>
005>
006> #define MAX_LINE_LENGTH 128
007> #define MAX_LINE_COUNT 1000
008>
009> int main(int argc, char **argv) {
010> char lines[MAX_LINE_COUNT][MAX_LINE_LENGTH];
011> int numLines = 0;
012>
013> if (argc < 2) {
014> fprintf(stderr, "missing file name\n");
015> return EXIT_FAILURE;
016> }
017>
018> FILE *fp = fopen(argv[1], "r");
019> if (fp != NULL) {
020> while (fgets(lines[numLines++], MAX_LINE_LENGTH, fp)) {
021> printf("%03d> %s", numLines, lines[numLines-1]);
022> }
023> fclose(fp);
024> srand (time(NULL));
025> int randomIndex = rand() % numLines;
026> printf("Selected random line #%d> %s", randomIndex+1, lines[randomIndex]);
027> } else {
028> fprintf(stderr, "file '%s' not found\n", argv[1]);
029> return EXIT_FAILURE;
030> }
031> }
Selected random line #2> #include <stdlib.h>

Read from a file and store it in 2d array

I am working on a function that reads from a file (fp) and stores in the words array. I declared MAX_WORD_SIZE as 128, but when I input any file into this function and check with valgrind, it tells me I have an uninitialized value in the line "while(getline(&line,&count,fp)!=-1)" I really don't get it: what is the uninitialised value? My fp file is valid and the word array is also declared well. Thank you in advance.
#include "functions.h"
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_file(FILE *fp, char words[][MAX_WORD_SIZE + 1], int size) {
int i=0;int j=0;
size_t count=MAX_WORD_SIZE;
char* line=malloc(MAX_WORD_SIZE);
while(getline(&line,&count,fp)!=-1){
for(;count>0;count--,j++){
sscanf(line,"%c",&words[i][j]);
}
i++;
}
int totalNums = i;
int totalNum = j;
if (i<size){
return 1;
}
fclose(fp);
return 0;
}
This is the function that I called this read_file function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
int main(int argc, char *argv[]) {
const char* fileName = argv[1];
FILE *fp = fopen(fileName, "r");
if (fp == NULL) {
printf("Invalid input file\n");
return 1;
}
int size = 0;
int validity = fscanf(fp, "%d", &size);
int returnValue = 0;
char words[size][MAX_WORD_SIZE + 1];
if(validity != 1 || size <= 0) {
printf("The first line is not a valid number\n");
return 1;
}
returnValue = read_file(fp, words, size);
if (returnValue == 1) {
fclose(fp);
return 1;
}
return 0;
}

File pointers led to core dump. Probably something stupid

Write the program myuniq.c that contains a function void process_file(FILE* f) that reads all input from the given file one line at the time while keeping two consecutive lines in memory, and prints each line to the standard output if it is not equal to the previously read line.
^^This is the assignment i'm working on. My code below is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process_file(FILE* f);
int main()
{
FILE *fil = fopen("text.txt","r");
process_file(fil);
return 0;
}
void process_file(FILE* f)
{
FILE *fi = f;
char *firstLine = fgets(firstLine, 999, f);
char *secondLine = fgets(secondLine, 999, f);
while (feof(fi))
{
if (firstLine == secondLine)
{
puts(secondLine);
}
else
{
puts(firstLine);
puts(secondLine);
}
firstLine++;
secondLine++;
}
}
It compiled fine...but on every run it says core dumped. I can't see where I went wrong? Any ideas?
You don't check the return value of fopen, you don't allocate any memory for the strings into which you read, you don't continue reading input from the file, you don't correctly check for the end of input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MY_MAX_LINE 999
void process_file(FILE* f)
{
char firstLine[MY_MAX_LINE + 1];
char secondLine[MY_MAX_LINE + 1];
while (1)
{
if (!fgets(firstLine, sizeof(firstLine), f))
break;
puts(firstLine);
if (!fgets(secondLine, sizeof(secondLine), f))
break;
if (strncmp(firstLine, secondLine, sizeof(firstLine)))
puts(secondLine);
}
if (!feof(f))
perror("Problem reading from file"), exit(1);
}
int main(int argc, char **argv)
{
FILE *f = fopen("text.txt", "r");
if (!f)
perror("text.txt"), exit(1);
process_file(f);
fclose(f);
return 0;
}

Reading Text In C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen( "Journey.txt" , "rt");
if(file){
while (fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else{
printf("Error");
}
return 1;
}
I want to read text file and use this code for adding BST.But If I run , Output is infinite loop.How can I read text file ?
Text file which I want to read:
80,15.04.2014,10,Henry Ford,NewYork,Paris,45
40,15.04.2014,11,Nikola Tesla,Londra,NewYork,40
Rather than read a text file using fscanf(), strongly recommend using fgets() and then parsing via sscanf(), strtok(), strtol(), etc. Check all function return values. It is much easier to cope with the unexpected - which is certainly what is happening in OP's case.
Using modified format from #BLUEPIXY
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main() {
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen("Journey.txt", "rt");
if (file) {
char buf[MAX*4 + 20*3 + 6*1 + 3];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int cnt = sscanf(buf, "%d,%499[^,],%d,%499[^,],%499[^,],%499[^,],%d",
&JourneyId, Date, &Hour, BusDriver, Departure, Destination,
&BusCapacity);
if (cnt != 7) {
printf("Unexpected input \"%s\"", buf);
break;
}
printf("%d,", JourneyId);
printf("%s\n", BusDriver);
}
fclose(file); // Be sure to close
} else {
printf("Error opening\n");
}
return 1;
}
As #BLUPIXY indicated, The following functions (tried on SuSE Linux / gcc)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE *file;
file = fopen( "Journey.txt" , "rt");
if(file)
{
// while(fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
while(fscanf(file,"%d,%11[^,],%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else
{
printf("Error");
}
return 1;
}

Resources