0

I am trying to print and read unsigned ints from a .txt file. I am using fprintf to print the unsigend int, (menualy checking the file presents the wanted values), but when reading it, I get a weird offset to all the values I read (same offset beween all reads, but not every run of the program), here is the reading code I am using:

unsigned int tempDuration = (unsigned int)fileFgets(file);

and this is fileFgets:

char tempStr[MAX_STR_SIZE] = { 0 };
char* str = 0;
fgets(tempStr, MAX_STR_SIZE, file);
tempStr[strcspn(tempStr, "\n")] = 0;
str = (char*)malloc(strlen(tempStr) * sizeof(str));
strcpy(str, tempStr);
return str;

I am using this function becuse it is ment to read both strings and unsinged ints, seperated by '\n', but am open for using diffrent solutions for both or either. (reading the strings works as intended)

Yoav Raman
  • 21
  • 6
  • 3
    You can't use a cast to convert a string to an integer. Use `strtoul()` or `sscanf()`. – Barmar Jun 22 '22 at 21:23
  • @Yoav Raman As you wrote the function should read unsigned integers from the file instead of strings. – Vlad from Moscow Jun 22 '22 at 21:24
  • 3
    Other issues: `strlen(tempStr)` needs to be `strlen(tempStr)+1` to account for the string NUL terminator. `sizeof(str)` should be `sizeof(*str)` or `sizeof(char)` – kaylum Jun 22 '22 at 21:25
  • 1
    Beware of memory leaks when allocating memory for the string like that. Also, if you need to allocate and copy a string, use `strdup` to avoid the very common issue that @kaylum already highlighted. – Cheatah Jun 22 '22 at 21:30
  • 1
    Does this answer your question? [How to convert a string to integer in C?](https://stackoverflow.com/questions/7021725/how-to-convert-a-string-to-integer-in-c) – kaylum Jun 22 '22 at 21:31
  • @kaylum fully, no. As I am using an unsinged int and not a normal one, but in my use case it is good enogh. – Yoav Raman Jun 28 '22 at 17:45

1 Answers1

0

Casting from an array of characters to an unsigned integer will actually cast the pointer and not the string itself. You need to convert it using strtoul().

Replacing the '\n' character isn't required because strtoul stopps at the first character which is not a valid digit.

I modified your function :

unsigned int fileFgets(file)
{
    char tempStr[MAX_STR_SIZE] = { 0 };
    fgets(tempStr, MAX_STR_SIZE, file);
    return strtoul(tempStr, NULL, 0);
}
Elzaidir
  • 891
  • 6
  • 13