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.
1 messages ยท Page 1 of 1 (latest)
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.
See strlen
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.
strlen in a function
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.
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
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.
thank you for this!
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
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.
@rustic reef Has your question been resolved? If so, run !solved :)
#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;
}
@rustic reef
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.
#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
wow ok there are a few weird things in what you pasted
oops thank you
I have changed simple = now still error
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 ?
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
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
I keep being told this but my brain doesn't understand how
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
dunno the purpose, but yeah it's not vital
so I would name a variable called char or is this vbuilt in within a pre directive
'char var there'? all one string ๐ confusion
so would i use char[filename] again
yes ok so filename is a string used to recognise to open the file
which user types in
i'm not sure
your usage of fgets function says something else
but i suppose you're not sure of what fgets does
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
you use the same variable for different purposes but ok
i'm talking about the second purpose
like a buffer i guess
when you fgets(filename...) you're storing data in filename
which variable?
filename
should I start again
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
ok..
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
I am curious:
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
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
so would I increment the value of len as fgets loop is working
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 ?
exactly
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
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
no you have to do a while inside the other while and forget about the existing strlen
you'll have to rewrite one
it's within a function that takes str as parameter so it's already declared, but you could also use it without a variable and do something like strlen("test string"), it would work cause I gave it a string
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
what do you mean
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
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
if you do strlen("string"), the whole things amounts to strlen return value, but if you do nothing with it it's lost
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?
kinda yeah
wdym
i will call strlen in another function, main for example providing it a **char * **with the name it has within main
char * means an address for a char
so would the address be filename?
implicitely the beginning of a string
ok thank you
yw
filename is a pointer to a char = a string and a pointer stores an address
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)
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
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
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;
}
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
using void ?
not too far from working yeah
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)
Nvm about that
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
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;
}
why would it be otherwise, it does the same thing except you named the variable differently lol
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
you mean the line above ?
what's your experience with programming ?
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
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
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
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?
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
you're somewhat doing that already, the thing is scanf puts the name of the file in "usersfile", but then you use fgets and put what you read in file input_file inside usersfile
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
but really, I want to put what I read into my array say char len?
ok great
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)
for some reason when I try to create a string, it does not work (doesnt change syntax and also comes up with error)
like how ?
ah
does not seem to recognise string
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
so doing char *tmp for example, would create a section of memory to store a string in? ๐ค
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
a pointer to where it would be stored, which i have no idea where lol
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
you did that already and it's ok to keep it that way
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
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)
{
}
```cpp
int main() {}
```
int main() {} ```
you mean something like a histogram that keeps track of how many of each character there are?
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
```cpp
int main() {}
```
int main() {} ```
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
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
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
I assumed, it would have to go by character by character anyway to count them ? or is this different to what we was doing initally?
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
don't worry I am just doing some reading now, thank you again for help
reading about functions step by step like you said
@rustic reef Has your question been resolved? If so, run !solved :)
Just something new
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);
}
man now it's just tripping me ๐
it worked, but that was the output lmao
tbf I haven't even wrote any output there
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;
}
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);
}
```cpp
int main() {}
```
int main() {} ```
ahahah
it's unnecessary to copy "filepath" to string, you could strlen(filepath) directly (although the var name isn't fit there)
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
<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
#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
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
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
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
something like this?
int strlen(char len[1000];) {
char *filepath = len)
while (*filepath++ ! = '\0' && !== space){
return len;
}
// 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);
&& !== is ill-formed and makes no sense
See "how to declare a function and why" and " how to define a function"
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++;
}
Yeah honestly if you have a hard time for 1. And 2. Then 3 and 4 are not going to be fun
ok well I've sorted one now I've gpne in uni how do i close this
my coding brain is awful lmao
We are monday
Getting there!!!
#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;
}
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?
Need help? Join the support server.