#Help with outputting characters from file

1 messages ยท Page 1 of 1 (latest)

narrow breachBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

quaint hedge
#

See strlen

narrow breachBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.

rustic reef
#

strlen?

#

function?

main lintel
#

strlen in a function

rustic reef
#

anyone know where I've gone wrong?

quaint hedge
#

Ah. Strlen measures length of a string. It's not an advanced function (it kinda is in fact). You re measuring the filename length before it gets a value.

rustic reef
#

by measuring the filename length, is this not how many characters are in that file? as I need to output number of lines in the file, which seems to have worked, then number of characters , excluding new lines , spaces and tabs

quaint hedge
#

You can strlen filename recursively in the fgets loop and add it to a sum

#

To excludea lines spaces and tabs you need to use isspace()

#

And write some strlen yourself using isspace. Nothing complicated.

rustic reef
#

thank you for this!

quaint hedge
#

A string is an array of char that ends with character 0

#

You re welcome

rustic reef
#

would I have to create another while within the while as I tried , do while but when I change current while loop to do it does not work

quaint hedge
#

Probably

#

Your string will be read entirely with an i++ loop, then you linecount(or the other way around), repeat everything until fgets = null

#

Within ++ loop you will count characters if they are not spaces until there's no more string.

narrow breachBOT
#

@rustic reef Has your question been resolved? If so, run !solved :)

rustic reef
#

#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//Author name is Isaac Warburton, purpose of this code is to read in a..
//csource file and output the following:
// 1) The total number of lines in the .c file (including any blank lines).
// 2) The number of characters in the .c file, excluding newlines, spaces and
//tabs.
// 3) The number of comments in the file.
// 4) The number of variables declared in the input .c file.

#define FILE_SIZE 1000

int main(int argc, char **argv)
{
//using memory allocation for filename
char filename[FILE_SIZE];
//initialising variable to store number of lines
int line_count= 0;
//intitialising variable to store total length of string
int len = 0;
//prompting user to enter file they wish to open
printf("Type File you wish to open: ");
scanf("%s", filename);
//open and reading file
FILE *input_file == fopen(filename, "r");
//error message for user input
if(input_file == NULL)
{
printf("Error, please try again.\n");
return 1;
}
//creating null operator for end of string.
else if(len > 0 && filename[len-1] = ";")
{
filename[len-1] = "\0";
while(fgets(filename,FILE_SIZE,input_file)!=NULL)
{
line_count = line_count +1;

}
}


    
printf("there are: %d lines in this file \n", line_count);
printf("There are: %d characters in this file \n", len);


fclose(input_file);
return 0;

}

narrow breachBOT
#

@rustic reef

Please Do Not Delete Posts!

Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.

rustic reef
#

#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//purpose of this code is to read in a..
//csource file and output the following:
// 1) The total number of lines in the .c file (including any blank lines).
// 2) The number of characters in the .c file, excluding newlines, spaces and
//tabs.
// 3) The number of comments in the file.
// 4) The number of variables declared in the input .c file.

#define FILE_SIZE 1000

int main(int argc, char **argv)
{
//using memory allocation for filename
char filename[FILE_SIZE];
//initialising variable to store number of lines
int line_count= 0;
//intitialising variable to store total length of string
int len = 0;
//prompting user to enter file they wish to open
printf("Type File you wish to open: ");
scanf("%s", filename);
//open and reading file
FILE *input_file == fopen(filename, "r");
//error message for user input
if(input_file == NULL)
{
printf("Error, please try again.\n");
return 1;
}
//creating null operator for end of string.
else if(len > 0 && filename[len-1] ==";")
{
filename[len-1] == "\0";
while(fgets(filename,FILE_SIZE,input_file)!=NULL)
{
line_count = line_count +1;

}
}


    
printf("there are: %d lines in this file \n", line_count);
printf("There are: %d characters in this file \n", len);


fclose(input_file);
return 0;

}

#

I'm just a bit confused with these erros

quaint hedge
#

wow ok there are a few weird things in what you pasted

rustic reef
#

oops thank you

quaint hedge
#

you used simple = to do an equality test

#

= is assignation

#

== is comparison

rustic reef
#

I have changed simple = now still error

quaint hedge
#

when you use double quotes you create a string, if you need to use character, you should use simple quotes

#

then you probably don't want to type that filename[len-1] = ";"

#

what's the idea behind that line ?

rustic reef
#

because the files end with ; but I have made filesize = 1000 at top using define, so I wanted to make sure that doesn't read all spaces after so I get correct character size

#

lol this is so hard

#

I ust got that from other code which was in work book

quaint hedge
#

ok

#

while(fgets(filename,FILE_SIZE,input_file)!=NULL)
{
line_count = line_count +1;

so, within that loop, you can count how many chars are in filename

rustic reef
#

I keep being told this but my brain doesn't understand how

quaint hedge
#

lol

#

you'll parse the string that way
while char[i]
i++

rustic reef
#

I guess that remove newline function is used actually probably to count how many lines there is but I guess I don't need it

quaint hedge
#

dunno the purpose, but yeah it's not vital

rustic reef
#

so I would name a variable called char or is this vbuilt in within a pre directive

quaint hedge
#

the char var there is a string

#

filename after each fgets call

rustic reef
#

'char var there'? all one string ๐Ÿ˜’ confusion

quaint hedge
#

char[]

#

it's actually a char array

rustic reef
#

ooooh you mean char as in like char a = b

#

okok

quaint hedge
#

yeah lol

#

character

rustic reef
#

so would i use char[filename] again

quaint hedge
#

no

#

filename is a string

#

not a valid index

rustic reef
#

yes ok so filename is a string used to recognise to open the file

#

which user types in

quaint hedge
#

i'm not sure

#

your usage of fgets function says something else

#

but i suppose you're not sure of what fgets does

rustic reef
#

oh but I have created it as a char .. char filename [FILE_ZISE] in order to be able to hold the whole file in array of characters i think

quaint hedge
#

you use the same variable for different purposes but ok

#

i'm talking about the second purpose

rustic reef
#

like a buffer i guess

quaint hedge
#

when you fgets(filename...) you're storing data in filename

rustic reef
#

which variable?

quaint hedge
#

filename

rustic reef
#

should I start again

quaint hedge
#

not necessarily

#

that being said i'm not sure if fgets works with char arrays instead of strings, probably does

#

so fgets stops after it reaches a newline

#

at that point it puts everything it found in filename, ok ?

#

that is, every character until & including '\n' is copied into filename

rustic reef
#

ok..

quaint hedge
#

wel

#

you might have wanted to count newlines with fgets

#

but that's a side effect

#

the main effect is that it's "GETting String"

#

from File

rustic reef
#

I am curious:

quaint hedge
#

so it fills the string given in first parameter with a number of character that is second parameter that it finds in third parameter that is a file it reads from

rustic reef
#

char filename[FILE_SIZE];
//initialising variable to store number of lines
int line_count= 0;
//intitialising variable to store total length of string
int len = strlen(filename);

#

are these two the same thing

#

because I was thinking they are different

quaint hedge
#

they're different

#

strlen counts every char except '\0' (which is when it stops)

rustic reef
#

so would I increment the value of len as fgets loop is working

quaint hedge
#

so if you count every char from filename everytime you succeed to fill it with data from file, you'll get the total number of char

#

you get the idea ?

quaint hedge
#

except...

#

you dont want to count spaces type characters

#

so you'll have to rewrite a custom strlen so you could filter them out

#

a simple implementation of strlen is the following :

#

int strlen(char *str)
{
int i = 0;
while str[i] != 0
i++;
return i
}

#

all you'd have to do is increment i only if isspace == 0

rustic reef
#

you have wrotewhile str[] os 'str' something you would have to decalre or does this just work

#

int len = char *filename)

#

?

#

not sure

#

while(fgets(filename,FILE_SIZE,input_file)!=NULL)
{
line_count = line_count +1;
len = len + 1;
}

#

i have to get the length of a line wach time new line then loop

#

hmmm

#

so maybe I need to save each line in variable which I have done line_lentgh

#

lamo I know this wont work

quaint hedge
#

no you have to do a while inside the other while and forget about the existing strlen

#

you'll have to rewrite one

quaint hedge
rustic reef
#

ok so how would i create one if I can't use filename

#

int strlen(char *str) // is this you creating one?

#

it's ok I'll take break now maybe try find some vids after

quaint hedge
rustic reef
#

if I did strlen(" this is a string") then printf(strlen()) idk if thats right, its easier because it would print the string lentgh of the string but how on earth do u do it print the string length (amount of chacaters in file) :' ) I will read all over this after clearly my head is not working

quaint hedge
# rustic reef int strlen(char *str) // is this you creating one?

this means there is a function called strlen that returns an int and takes a char * as parameter that will be accessed and worked on within the function everytime i call it using str.

i will call strlen in another function, main for example providing it a char * with the name it has within main

quaint hedge
rustic reef
#

ok so it doesnt get stored it's too quick

#

xD

quaint hedge
#

you could do printf("%d", strlen(string))

#

or var =strlen then printf("%d", var)

rustic reef
#

so it takes a char * and then returns it as a number, but number of characters right? not like the ascii value of the char

#

and char * ( what would I need to point to) char *filename?

rustic reef
#

what is the pointer for char

#

char *

quaint hedge
#

i dont understand the question sorry

#

what is it where ?

rustic reef
#

i will call strlen in another function, main for example providing it a **char * **with the name it has within main

quaint hedge
#

char * means an address for a char

rustic reef
#

so would the address be filename?

quaint hedge
#

implicitely the beginning of a string

rustic reef
#

ok thank you

quaint hedge
#

yw

quaint hedge
#

well, here it's an array of char

#

but sometimes they're interchangeable, sometimes not

#

they have different properties

#

(I'm not an expert on the nuances there, reading the errors the compiler provides is usually enough to rework properly)

rustic reef
#

ah man I've tried so many hours watching stuff, just how to get amount of characters really just not seem to be understanding ill try again later

#

thank you for all your help

quaint hedge
#

yw

#

but i told you how to achieve it

#

count chars with a custom strlen(filename) (that means rewrite it to be conditional so that it increments only if checked character is not a space (if isspace(char[i]) == 0))

#

it's really that simple

#

if you translate that exactly into code it should work

#

but yeah taking breaks is sometimes for the best

rustic reef
#

char i[filename] = i++;

#

so far I worte this

#

I am confused with this strlen thing too much

#

thank you I will do it let you know if it works later

#

while(fgets(filename,FILE_SIZE,input_file)!=NULL)
{
line_count = line_count +1;
int c = 0;
while (filename[c] != 0)
c++;
return c;

     }
#

while(fgets(filename,FILE_SIZE,input_file)!=NULL)
{
line_count = line_count +1;
while (filename[c] != 0 && != " ")
characters++;
return characters;

     }
rustic reef
#

ok im back my brain has awoken and i understand everything u was saying ๐Ÿ˜‚ so *str represents the string variable , in order to rewrite it , as u mean not use the one which is in the <string> directive , so create int strlen(char *filename)

#

and then the while you spoke about to filter out

#

i guess i could create this using void

quaint hedge
#

using void ?

quaint hedge
#

increment c, reset it to 0 once you're outside of the inside loop

#

and that kinda works (use ' instead of ", and maybe filer out newlines too)

rustic reef
rustic reef
#

int main(int argc, char **argv)
{
char filename[FILE_SIZE];
char line[1000];
int line_count = 0;
int char_count = 0;
int n = 0;
printf("Type File you wish to open: ");
scanf("%s", filename);

    FILE *input_file = fopen(filename, "r");
    if(input_file == NULL)
    {
        printf("Error, please try again.\n");
        return 1;
    }

     while(fgets(filename,FILE_SIZE,input_file)!=NULL)
     {
            
     while(fgets(line, 1000, input_file))
     {
            line_count = line_count +1;
            char_count = char_count +1;
     }
        
        
    
    
     }
  
    printf("there are: %d lines in this file \n", line_count);
    printf("there are: %d characters in this file \n", char_count);
          
    fclose(input_file);
    return 0;

}

#

this is my new code but it seems to print amount of lines for both

narrow breachBOT
#
int main(int argc, char** argv) {
  char filename[FILE_SIZE];
  char line[1000];
  int line_count = 0;
  int char_count = 0;
  int n = 0;
  printf("Type File you wish to open: ");
  scanf("%s", filename);

  FILE* input_file = fopen(filename, "r");
  if (input_file == NULL) {
    printf("Error, please try again.\n");
    return 1;
  }

  while (fgets(filename, FILE_SIZE, input_file) != NULL) {
    while (fgets(line, 1000, input_file)) {
      line_count = line_count + 1;
      char_count = char_count + 1;
    }
  }

  printf("there are: %d lines in this file \n", line_count);
  printf("there are: %d characters in this file \n", char_count);

  fclose(input_file);
  return 0;
}
braintalks
quaint hedge
#

why would it be otherwise, it does the same thing except you named the variable differently lol

rustic reef
#

lmao

#

I was trying to make second array to store the line that has been read in to

#

idk how i would store it

#

while (filename[c] != 0 && != " ")

#

here what exactly does this do

#

i am hopeless man no matter how many times i read i cant get it fml

quaint hedge
#

what's your experience with programming ?

rustic reef
#

access course 1 year basic c++ then 1st semester we did introduction to java, 2nd semester this. Just started uni in september I missed the first 4 weeks of lectures so i'm behind, been trying to catch up this corsework is due in 10 days and theres a lot more to do

#

I'v studying cyber security I like networking, and im creative however logic is not my strong point i also have adhd so get very easily muddled

#

FILE *file;
char usersfile[FILE_SIZE];
int line_count = 0;
char len[1000];

//open file
    printf("Type File you wish to open: ");
    scanf("%s", usersfile);
    
    FILE *input_file = fopen(usersfile, "r");
    if(input_file == NULL)
    {
        printf("Error, please try again.\n");
        return 1;
    }
    while(fgets(usersfile,FILE_SIZE,input_file)!=NULL)
     {
        line_count = line_count +1;
        
    if 
    while(len,1000,input_file)
    {
        
    }
        
     }
#

this is what I'm trying now

quaint hedge
#

ok

#

so

#

let's do things a bit cleaner then

#

right there you're putting the name of the file in the same variable that you use to store the file's content, at this point I think it can be confusing for you

rustic reef
#

FILE file;
char usersfile[FILE_SIZE];

#

here?

quaint hedge
#

when you use a function, you need to make sure you read stuff about that function, like how it works precisely

#

typically, if you're using windows, type man "name of the function" in google and read that old school text you find, cause it explains what matters

rustic reef
#

yes ok, I have bene watching and reading videos of fgets , strlen I did but still confused. however fgets, seems to get the number of characters within an array, or continues until there is a newline or 0?

quaint hedge
#

if you take your time and read manual, it's pretty clear what they explain

#

gets less confusing than videos

#

it's intended to be enough in an age there was nothing else

quaint hedge
#

so, usersfile has a size that's enough for a path, so you can keep it that way, or rename it filepath, because it's clearer

rustic reef
#

but really, I want to put what I read into my array say char len?

quaint hedge
#

len isn't clear

#

len means length so it should be a numeric value

#

not a string

rustic reef
#

ok great

quaint hedge
#

you can make another var called char *tmp for example, or string, or whatever tells what it does

#

what it does is acts like a buffer that stores strings until newline or EOF (end of file)

rustic reef
#

for some reason when I try to create a string, it does not work (doesnt change syntax and also comes up with error)

quaint hedge
#

like how ?

rustic reef
quaint hedge
#

ah

rustic reef
#

does not seem to recognise string

quaint hedge
#

string isn't valid type in C

#

char * = string

#

the thing is if you declare it that way, it's becoming a constant'ish string

#

you cannot modify it any way you want

rustic reef
#

so doing char *tmp for example, would create a section of memory to store a string in? ๐Ÿค”

quaint hedge
#

so using char arrays with a given range is ok, using that same range as the "n" value expected in fgets, maybe n - 1 i'm not sure about the good way

rustic reef
#

a pointer to where it would be stored, which i have no idea where lol

quaint hedge
#

it would create a pointer to a char, and at that point it has no value or garbage value cause uninitialized

#

enters "malloc" function

#

malloc(size of desired memory allocation) will reserve the memory for your variable, that is create a starting point up to an end point

#

just know that malloc is often unsafe because if memory was used for something else and is read without having being rewritten, it's gonna be a problem

#

but if your code is clean, this shouldn't happen (I think)

#

But you can use an alternative that is "calloc"

#

it will initialize the memory to 0 bits

#

anything you malloc must be freed

#

way it works is :
var = malloc(size);
stuff happens with your var
you're done with it, before exiting main you have to:
free(var)

#

but you dont need malloc there

quaint hedge
#

but if you're learning C, you'll have to manage malloc

#

fgets(usersfile,FILE_SIZE,input_file)!=NULL)
when you do this suppose input_file is something like
"yesterday I went to the beach\n (representing the newline AND typing it, but that's for the sake of illustration)
tomorrow I plan to go to the cinema\0 (this is end of file)"
fgets returns usersfile AND writes in it
then the first time you call fgets, usersfile will be == to "yesterday I went to the beach\n", before you're calling the loop again, you can work on that usersfile string to count characters, or anything else, then second call it's "tomorrow I plan to go to the cinema\0", the third call it's NULL

rustic reef
#

thank you for all this info man, awesome - really appreciate it

#

by you did this already do you mean, where I have created a variable and initialised its value '=0'? or when I defined #FILE_SIZE[1000]?

#

also I'm only using input_file, as it was given on one of our powerpoints when demonstrating, opening and reading a file. Yet, I find it confusing because input_file, has not been initialised, or is that a parameter within one of the #include functions

#

if I was to create an array named characters[filepath]. Would this mean I was creating an array within the file, which I would then use to store the characters? These would be then stored within the memory location of the file.

#

lol I don't know if that makes sense

#

if I did this within a function that returned a value, say void(char characters[filepath], int i = 0) where i would represent each time a character is stored... within that function I would have to create some code i increments except there is a newline, space or tab. ?

#

void int count_characters(char ch[filepath], int i = 0)
{
while(fgets(filepath,FILE_SIZE,input_file)!=NULL)
{

}
narrow breachBOT
#
How to Format Code on Discord
Markup

```cpp
int main() {}
```

Result
int main() {} ```
thin ingot
#

you'd need to make something like a int histogram[UCHAR_MAX + 1] to keep track for each

#

but if you only want to keep track of how much whitespace there is, a single int is enough

narrow breachBOT
#
How to Format Code on Discord
Markup

```cpp
int main() {}
```

Result
int main() {} ```
rustic reef
#

I was thinking something like along them lines, but don't think this would work, as probably not used fget right. However, that histogram idea sounds interesting

thin ingot
#

I don't get why you would have two characters there

#

if you're going character by character, you can actually just read with fgetc

rustic reef
#

I also really struggle with arrays, haven't grasped them yet. I am wondering how what variables I would use, and so on in order to actually crate a characters array and how I would use it store characters ๐Ÿ˜‚ I have avoided arrays throughout any stuff I've done so far

rustic reef
thin ingot
#

if you're using fgets, then you first have to store the line in a buffer, then go character by character

#

but you can also go character by character within the file

rustic reef
#

don't worry I am just doing some reading now, thank you again for help

#

reading about functions step by step like you said

narrow breachBOT
#

@rustic reef Has your question been resolved? If so, run !solved :)

rustic reef
#

Just something new

narrow breachBOT
#
int main(int argc, char** argv) {
  char filepath[FILE_SIZE];
  char characters[1000];
  int line_count = 0;
  // open file
  printf("Type File you wish to open: ");
  scanf("%s", filepath);

  FILE* input_file = fopen(filepath, "r");
  if (input_file == NULL) {
    perror("Error, please try again.\n");
    return (-1);
  }

        if ( !=NULL (fgets (filepath,FILE_SIZE,input_file)  )
        {
    /*writing content to stdout */
    puts(characters);
        }
             
    fclose(input_file);
   
   return (0);
}
braintalks
thin ingot
#

oh oops, that got rid of the image

#

if ( !=NULL doesn't look quite right

rustic reef
#

man now it's just tripping me ๐Ÿ˜‚

#

it worked, but that was the output lmao

#

tbf I haven't even wrote any output there

narrow breachBOT
#
int main(int argc, char** argv) {
  char filepath[FILE_SIZE];
  char characters[1000];
  int line_count = 0;
  // open file
  printf("Type File you wish to open: ");
  scanf("%s", filepath);

  // opening file for reading

  FILE* fileptr = fopen(filepath, "r");
  if (fileptr == NULL) {
    perror("File could not open");
    return (-1);
  }

  if (fgets(filepath, FILE_SIZE, fileptr) != NULL) {
    puts(characters);
  }

  fclose(fileptr);

  return 0;
}
braintalks
rustic reef
#

how do you use format?

#

also what do you think of this logic

#

while(fgets (filepath,FILE_SIZE,fileptr) !=NULL){

    //each time line is read, filepath increments by 1
    line_count = line_count + 1;
    
}
while((fgets (filepath,FILE_SIZE,fileptr) ==NULL)
{
    strcpy(string,filepath);
    char_count = strlen(string);
    
}
thin ingot
#

but you should just format your code yourself

narrow breachBOT
#
How to Format Code on Discord
Markup

```cpp
int main() {}
```

Result
int main() {} ```
rustic reef
#

'''cpp int main(){

#

lol

opal patioBOT
#
Critical error:

No main() specified. Invalid request

#

Hello! I can compile code for you. To compile code, first post a code block containing code, right click the message, go to the Apps dropdown, and select the Compile option!

If you are unfamiliar with Markdown, codeblocks can be created by formatting your message as the following.
```
<code>
```

quaint hedge
quaint hedge
#

and you should type charcount += strlen(filepath), but that will include every character including whitespaces & silent ones

#

a solution based on getchar like Eisen mentioned is fit cause you can apply filters directly on it, increasing linecount when char == \n, and count char only if isascii

opal patioBOT
#
Compiler Output
<source>:3:20: warning: extra tokens at end of #include directive
    3 | #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define FILE_SIZE 1000 //create strlen function     //reads in file , line by line and stores into pointer file  while(fgets (filepath,FILE_SIZE,fileptr) !=NULL){      //each time '\n' is read, increases linecount by 1     line_count = line_count + 1;   //stops line count when end-of-file is encountered, /0 null is returned  }    int length = strlen(filepath);  char string[FILE_SIZE];  int counted = 0;    for (int i = 0; i < length; i ++){      bool already_counted = false;      for(int j = 0; j < counted; j++){        if(filepath[i] == string[j])         already_counted = true;       if(already_counted) continue;      int count = 0;   for(int j = 0; j < length; j++)       if(filepath[i] == string[j]) count++;      printf("%s - %d\n", string, count);   string[char_count] = filepath[i];   counted++;   }  }  printf("Total lines in th
rustic reef
#

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define FILE_SIZE 1000
//create strlen function

int main(int argc, char **argv)
{

char filepath[FILE_SIZE];
int line_count = 0;
int char_count = 0;
//open file
printf ( "Type File you wish to open: " );
scanf ( "%s", filepath );

//opening file for reading

FILE *fileptr = fopen(filepath, "r");
if (fileptr == NULL) {
    
    perror("File could not open");
    return(-1);
    
}
//reads in file , line by line and stores into pointer file
while(fgets (filepath,FILE_SIZE,fileptr) !=NULL){
    
    //each time '\n' is read, increases linecount by 1        
    line_count = line_count + 1;
    //stops line count when end-of-file is encountered, /0 null is returned
}

int length = strlen(filepath);
char string[FILE_SIZE];
int counted = 0;

for (int i = 0; i < length; i ++){
    
    bool already_counted = false;
    
    for(int j = 0; j < counted; j++){
        
        if(filepath[i] == string[j])
            
        already_counted = true;
        
    if(already_counted) continue;
    
    int count = 0;
    for(int j = 0; j < length; j++)
        
    if(filepath[i] == string[j]) count++;
    
    printf("%s - %d\n", string, count);
    string[char_count] = filepath[i];
    counted++;
    }
}
printf("Total lines in this file are: %d \n", line_count);


fclose(fileptr);

return 0;
}
#

just got this stuff from a vid again, as it seemed to make sense with the looping not working though

quaint hedge
#

man I think you should stop trying to copy paste code

#

you must type small code, see how it works and then build upon it

#

little by little you can make things complex, and understand everything, but if you fetch large parts of code, you'll miss things or understanding points

rustic reef
#

I am starting to undersdtand more, I am just still confused with strlen function. As seriously how do I create it as it wont let me make something called like int length =strlen(filepath) I need to find away, how to store what is read, into filepath and move that into something that I can store strlen in

#

lol

#

it's not even that I don't understand it, all exampled online use a string that is already declared "i am a string" none seem to use a full file thats been read. Also I have tried using strcpy function, to copy filename into a new char string[1000] for example. and it doesnt work

quaint hedge
#

you must read the compiler error

#

strlen doesn't return an int

#

iirc it's a ssize_t

#

I suggested that you create a custom strlen function that returns an int, which should be enough because you'll measure a string shorter than 1000 chars

#

why do you want to store what's read ? it's already stored in filepath

rustic reef
#

something like this?

narrow breachBOT
#
int strlen(char len[1000];) {
        char *filepath = len)
        while (*filepath++ ! = '\0' && !== space){
          return len;
        }
braintalks
#
// reads in file , line by line and stores into pointer file
while (fgets(filepath, FILE_SIZE, fileptr) != NULL) {
  // each time '\n' is read, increases linecount by 1
  line_count = line_count + 1;
  // stops line count when end-of-file is encountered, /0 null is returned
}
int strlen(length);
{
  while (*filepath++ != '\0') {
    length = *filepath;
        printf("%d", strlen(length);
braintalks
thin ingot
#

&& !== is ill-formed and makes no sense

rustic reef
#

lol

#

ok i will look at operaters properly

quaint hedge
#

See "how to declare a function and why" and " how to define a function"

narrow breachBOT
#

FILE *fileptr = fopen(filepath, "r");
```cpp
if (fileptr == NULL) {
perror("File could not open");
return (-1);
}
while (fgets(filepath, FILE_SIZE, fileptr) != NULL) {
// each time '\n' is read, increases linecount by 1
line_count = line_count + 1;
// stops line count when /0 null is returned
}
int totalc = 0;
char c;
while( (c = fgetc(filepath)!= '\0' ){
if (!isspace(c))
totalc++;

}
braintalks
quaint hedge
#

well, it would be safer to use "isalnum" in that case

#

but yeah

rustic reef
#

isalnum?

#

this is due monday I am so fucked lol

quaint hedge
#

Yeah honestly if you have a hard time for 1. And 2. Then 3 and 4 are not going to be fun

rustic reef
#

ok well I've sorted one now I've gpne in uni how do i close this

#

my coding brain is awful lmao

quaint hedge
#

We are monday

rustic reef
#

Getting there!!!

narrow breachBOT
#
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_BUFFER 1000
// create strlen function

int main(int argc, char** argv) {
  char* removec = " \t\n";
  char* token;
  char filestr[FILE_BUFFER];
  // open file
  printf("Type File you wish to open: ");
  scanf("%s", filestr);

  // opening file for reading

  FILE* testfile = fopen(filestr, "r");
  int line_count = 0;
  int char_count = 0;
  int comment_count = 0;
  char* search_comment = "//";

  if (testfile == NULL) {
    perror("File could not open");
    return (-1);

  }  // enf of if statement

  // while loop to read in file using fgets function
  while (fgets(filestr, FILE_BUFFER, testfile) != NULL) {
    line_count = line_count + 1;
    token = strtok(filestr, removec);
    // inner while loop to tokenise each line, counting characters and comments
    while (token != NULL) {
      // counter
      char_count = strlen(token) + char_count;
      if (strcmp(token, search_comment) == 0) {
        comment_count = comment_count + 1;

      }  // end of if

      token = strtok(NULL, removec);

    }  // end of token while

  }  // end of outer loop

  printf("Total lines in this file are: %d \n", line_count);
  printf("Total characters in this file are: %d \n", char_count);
  printf("Total comments in this file are: %d \n", comment_count);
  fclose(testfile);

  return 0;
}
braintalks
jovial forgeBOT
#

Hi! I am a bot for DISBOARD (https://disboard.org)

COMMAND LIST

/help: This!
/bump: Bump this server.
/page: Get a link to the server's DISBOARD page.
/invite [channel]: Set invite to this channel. If [channel] is specified, create an invite for that channel. (Admin only.)

How do I add my server to DISBOARD?

  1. Login on DISBOARD website,
  2. Go to Dashboard,
  3. Click "Add New Server"
    Fill out your server info and save it. You will be redirected to Discord's authorization screen. If not, click the "Add Bot" button on the server edit page.

Need help? Join the support server.

rustic reef
#

close chat

#

!solved